FlatCAMApp.py 355 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import urllib.request, urllib.parse, urllib.error
  9. import getopt
  10. import random
  11. import simplejson as json
  12. import lzma
  13. import threading
  14. from stat import S_IREAD, S_IRGRP, S_IROTH
  15. import subprocess
  16. import tkinter as tk
  17. from PyQt5 import QtPrintSupport
  18. import urllib.request, urllib.parse, urllib.error
  19. from contextlib import contextmanager
  20. import gc
  21. from xml.dom.minidom import parseString as parse_xml_string
  22. ########################################
  23. ## Imports part of FlatCAM ##
  24. ########################################
  25. from ObjectCollection import *
  26. from FlatCAMObj import *
  27. from flatcamGUI.PlotCanvas import *
  28. from flatcamGUI.FlatCAMGUI import *
  29. from FlatCAMCommon import LoudDict
  30. from FlatCAMPostProc import load_postprocessors
  31. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  32. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  33. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  34. from FlatCAMProcess import *
  35. from FlatCAMWorkerStack import WorkerStack
  36. from flatcamGUI.VisPyVisuals import Color
  37. from vispy.gloo.util import _screenshot
  38. from vispy.io import write_png
  39. from flatcamTools import *
  40. from multiprocessing import Pool
  41. import tclCommands
  42. import gettext
  43. import FlatCAMTranslation as fcTranslate
  44. fcTranslate.apply_language('strings')
  45. import builtins
  46. if '_' not in builtins.__dict__:
  47. _ = gettext.gettext
  48. ########################################
  49. ## App ##
  50. ########################################
  51. class App(QtCore.QObject):
  52. """
  53. The main application class. The constructor starts the GUI.
  54. """
  55. # Get Cmd Line Options
  56. cmd_line_shellfile = ''
  57. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  58. try:
  59. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  60. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  61. except getopt.GetoptError:
  62. print(cmd_line_help)
  63. sys.exit(2)
  64. for opt, arg in cmd_line_options:
  65. if opt == '-h':
  66. print(cmd_line_help)
  67. sys.exit()
  68. elif opt == '--shellfile':
  69. cmd_line_shellfile = arg
  70. # Logging ##
  71. log = logging.getLogger('base')
  72. log.setLevel(logging.DEBUG)
  73. # log.setLevel(logging.WARNING)
  74. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  75. handler = logging.StreamHandler()
  76. handler.setFormatter(formatter)
  77. log.addHandler(handler)
  78. # Version
  79. version = 8.913
  80. version_date = "2019/03/25"
  81. beta = True
  82. # current date now
  83. date = str(datetime.today()).rpartition('.')[0]
  84. date = ''.join(c for c in date if c not in ':-')
  85. date = date.replace(' ', '_')
  86. # URL for update checks and statistics
  87. version_url = "http://flatcam.org/version"
  88. # App URL
  89. app_url = "http://flatcam.org"
  90. # Manual URL
  91. manual_url = "http://flatcam.org/manual/index.html"
  92. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  93. # this variable will hold the project status
  94. # if True it will mean that the project was modified and not saved
  95. should_we_save = False
  96. # flag is True if saving action has been triggered
  97. save_in_progress = False
  98. ##################
  99. ## Signals ##
  100. ##################
  101. # Inform the user
  102. # Handled by:
  103. # * App.info() --> Print on the status bar
  104. inform = QtCore.pyqtSignal(str)
  105. app_quit = QtCore.pyqtSignal()
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. ###################
  149. ### OS-specific ###
  150. ###################
  151. # Folder for user settings.
  152. if sys.platform == 'win32':
  153. from win32com.shell import shell, shellcon
  154. if platform.architecture()[0] == '32bit':
  155. App.log.debug("Win32!")
  156. else:
  157. App.log.debug("Win64!")
  158. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\FlatCAM'
  159. self.os = 'windows'
  160. else: # Linux/Unix/MacOS
  161. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  162. self.os = 'unix'
  163. ###############################
  164. ### Setup folders and files ###
  165. ###############################
  166. if not os.path.exists(self.data_path):
  167. os.makedirs(self.data_path)
  168. App.log.debug('Created data folder: ' + self.data_path)
  169. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  170. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  171. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  172. if not os.path.exists(self.postprocessorpaths):
  173. os.makedirs(self.postprocessorpaths)
  174. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  175. # create current_defaults.FlatConfig file if there is none
  176. try:
  177. f = open(self.data_path + '/current_defaults.FlatConfig')
  178. f.close()
  179. except IOError:
  180. App.log.debug('Creating empty current_defaults.FlatConfig')
  181. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  182. json.dump({}, f)
  183. f.close()
  184. # create factory_defaults.FlatConfig file if there is none
  185. try:
  186. f = open(self.data_path + '/factory_defaults.FlatConfig')
  187. f.close()
  188. except IOError:
  189. App.log.debug('Creating empty factory_defaults.FlatConfig')
  190. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  191. json.dump({}, f)
  192. f.close()
  193. try:
  194. f = open(self.data_path + '/recent.json')
  195. f.close()
  196. except IOError:
  197. App.log.debug('Creating empty recent.json')
  198. f = open(self.data_path + '/recent.json', 'w')
  199. json.dump([], f)
  200. f.close()
  201. # Application directory. CHDIR to it. Otherwise, trying to load
  202. # GUI icons will fail as their path is relative.
  203. # This will fail under cx_freeze ...
  204. self.app_home = os.path.dirname(os.path.realpath(__file__))
  205. App.log.debug("Application path is " + self.app_home)
  206. App.log.debug("Started in " + os.getcwd())
  207. # cx_freeze workaround
  208. if os.path.isfile(self.app_home):
  209. self.app_home = os.path.dirname(self.app_home)
  210. os.chdir(self.app_home)
  211. # Create multiprocessing pool
  212. self.pool = Pool()
  213. # variable to store mouse coordinates
  214. self.mouse = [0, 0]
  215. ####################
  216. ## Initialize GUI ##
  217. ####################
  218. # FlatCAM colors used in plotting
  219. self.FC_light_green = '#BBF268BF'
  220. self.FC_dark_green = '#006E20BF'
  221. self.FC_light_blue = '#a5a5ffbf'
  222. self.FC_dark_blue = '#0000ffbf'
  223. QtCore.QObject.__init__(self)
  224. self.ui = FlatCAMGUI(self.version, self.beta, self)
  225. # self.connect(self.ui,
  226. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  227. # self.save_geometry) PyQt4
  228. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  229. self.ui.final_save.connect(self.final_save)
  230. ##############
  231. #### Data ####
  232. ##############
  233. self.recent = []
  234. self.clipboard = QtWidgets.QApplication.clipboard()
  235. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  236. self.project_filename = None
  237. self.toggle_units_ignore = False
  238. # self.defaults_form = PreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. # General App
  243. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  244. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  245. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  246. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  247. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  248. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  249. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  250. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  251. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  252. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  253. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  254. "global_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:
  1812. self.inform.emit(_("[WARNING] Object empty after edit."))
  1813. elif isinstance(edited_obj, FlatCAMGerber):
  1814. obj_type = "Gerber"
  1815. if cleanup is None:
  1816. self.grb_editor.update_fcgerber(edited_obj)
  1817. self.grb_editor.update_options(edited_obj)
  1818. self.grb_editor.deactivate()
  1819. # update the geo object options so it is including the bounding box values
  1820. try:
  1821. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1822. edited_obj.options['xmin'] = xmin
  1823. edited_obj.options['ymin'] = ymin
  1824. edited_obj.options['xmax'] = xmax
  1825. edited_obj.options['ymax'] = ymax
  1826. except AttributeError:
  1827. self.inform.emit(_("[WARNING] Object empty after edit."))
  1828. elif isinstance(edited_obj, FlatCAMExcellon):
  1829. obj_type = "Excellon"
  1830. if cleanup is None:
  1831. self.exc_editor.update_fcexcellon(edited_obj)
  1832. self.exc_editor.update_options(edited_obj)
  1833. self.exc_editor.deactivate()
  1834. else:
  1835. self.inform.emit(_("[WARNING_NOTCL] Select a Gerber, Geometry or Excellon Object to update."))
  1836. return
  1837. # if notebook is hidden we show it
  1838. if self.ui.splitter.sizes()[0] == 0:
  1839. self.ui.splitter.setSizes([1, 1])
  1840. # restore the call_source to app
  1841. self.call_source = 'app'
  1842. edited_obj.plot()
  1843. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1844. self.ui.plot_tab_area.protectTab(0)
  1845. self.inform.emit(_("[selected] %s is updated, returning to App...") % obj_type)
  1846. # reset the Object UI to original settings
  1847. # edited_obj.set_ui(edited_obj.ui_type())
  1848. # edited_obj.build_ui()
  1849. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1850. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1851. def get_last_folder(self):
  1852. return self.defaults["global_last_folder"]
  1853. def get_last_save_folder(self):
  1854. loc = self.defaults["global_last_save_folder"]
  1855. if loc is None:
  1856. loc = self.defaults["global_last_folder"]
  1857. if loc is None:
  1858. loc = os.path.dirname(__file__)
  1859. return loc
  1860. def report_usage(self, resource):
  1861. """
  1862. Increments usage counter for the given resource
  1863. in self.defaults['global_stats'].
  1864. :param resource: Name of the resource.
  1865. :return: None
  1866. """
  1867. if resource in self.defaults['global_stats']:
  1868. self.defaults['global_stats'][resource] += 1
  1869. else:
  1870. self.defaults['global_stats'][resource] = 1
  1871. def init_tcl(self):
  1872. if hasattr(self,'tcl'):
  1873. # self.tcl = None
  1874. # TODO we need to clean non default variables and procedures here
  1875. # new object cannot be used here as it will not remember values created for next passes,
  1876. # because tcl was execudted in old instance of TCL
  1877. pass
  1878. else:
  1879. self.tcl = tk.Tcl()
  1880. self.setup_shell()
  1881. self.log.debug("TCL Shell has been initialized.")
  1882. # TODO: This shouldn't be here.
  1883. class TclErrorException(Exception):
  1884. """
  1885. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1886. """
  1887. pass
  1888. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1889. """
  1890. Shows a message on the FlatCAM Shell
  1891. :param msg: Message to display.
  1892. :param show: Opens the shell.
  1893. :param error: Shows the message as an error.
  1894. :return: None
  1895. """
  1896. if show:
  1897. self.ui.shell_dock.show()
  1898. try:
  1899. if error:
  1900. self.shell.append_error(msg + "\n")
  1901. elif warning:
  1902. self.shell.append_warning(msg + "\n")
  1903. elif success:
  1904. self.shell.append_success(msg + "\n")
  1905. elif selected:
  1906. self.shell.append_selected(msg + "\n")
  1907. else:
  1908. self.shell.append_output(msg + "\n")
  1909. except AttributeError:
  1910. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1911. def raise_tcl_unknown_error(self, unknownException):
  1912. """
  1913. Raise exception if is different type than TclErrorException
  1914. this is here mainly to show unknown errors inside TCL shell console.
  1915. :param unknownException:
  1916. :return:
  1917. """
  1918. if not isinstance(unknownException, self.TclErrorException):
  1919. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1920. else:
  1921. raise unknownException
  1922. def display_tcl_error(self, error, error_info=None):
  1923. """
  1924. escape bracket [ with \ otherwise there is error
  1925. "ERROR: missing close-bracket" instead of real error
  1926. :param error: it may be text or exception
  1927. :return: None
  1928. """
  1929. if isinstance(error, Exception):
  1930. exc_type, exc_value, exc_traceback = error_info
  1931. if not isinstance(error, self.TclErrorException):
  1932. show_trace = 1
  1933. else:
  1934. show_trace = int(self.defaults['global_verbose_error_level'])
  1935. if show_trace > 0:
  1936. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1937. trc_formated = []
  1938. for a in reversed(trc):
  1939. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1940. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1941. exc_type,
  1942. "\n".join(trc_formated))
  1943. else:
  1944. text = "%s" % error
  1945. else:
  1946. text = error
  1947. text = text.replace('[', '\\[').replace('"', '\\"')
  1948. self.tcl.eval('return -code error "%s"' % text)
  1949. def raise_tcl_error(self, text):
  1950. """
  1951. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1952. :param text: text of error
  1953. :return: raise exception
  1954. """
  1955. self.display_tcl_error(text)
  1956. raise self.TclErrorException(text)
  1957. def exec_command(self, text):
  1958. """
  1959. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1960. Also handles execution in separated threads
  1961. :param text:
  1962. :return: output if there was any
  1963. """
  1964. self.report_usage('exec_command')
  1965. result = self.exec_command_test(text, False)
  1966. #MS: added this method call so the geometry is updated once the TCL
  1967. #command is executed
  1968. self.plot_all()
  1969. return result
  1970. def exec_command_test(self, text, reraise=True):
  1971. """
  1972. Same as exec_command(...) with additional control over exceptions.
  1973. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1974. :param text: Input command
  1975. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1976. :return: Output from the command
  1977. """
  1978. text = str(text)
  1979. try:
  1980. self.shell.open_proccessing() # Disables input box.
  1981. result = self.tcl.eval(str(text))
  1982. if result != 'None':
  1983. self.shell.append_output(result + '\n')
  1984. except tk.TclError as e:
  1985. # This will display more precise answer if something in TCL shell fails
  1986. result = self.tcl.eval("set errorInfo")
  1987. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1988. self.shell.append_error('ERROR: ' + result + '\n')
  1989. # Show error in console and just return or in test raise exception
  1990. if reraise:
  1991. raise e
  1992. finally:
  1993. self.shell.close_proccessing()
  1994. pass
  1995. return result
  1996. # """
  1997. # Code below is unsused. Saved for later.
  1998. # """
  1999. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2000. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2001. # self.log.debug(parts)
  2002. # try:
  2003. # if parts[0] not in commands:
  2004. # self.shell.append_error("Unknown command\n")
  2005. # return
  2006. #
  2007. # #import inspect
  2008. # #inspect.getargspec(someMethod)
  2009. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2010. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2011. # self.shell.append_error(
  2012. # "Command %s takes %d arguments. %d given.\n" %
  2013. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2014. # )
  2015. # return
  2016. #
  2017. # cmdfcn = commands[parts[0]]["fcn"]
  2018. # cmdconv = commands[parts[0]]["converters"]
  2019. # if len(parts) - 1 > 0:
  2020. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2021. # else:
  2022. # retval = cmdfcn()
  2023. # retfcn = commands[parts[0]]["retfcn"]
  2024. # if retval and retfcn(retval):
  2025. # self.shell.append_output(retfcn(retval) + "\n")
  2026. #
  2027. # except Exception as e:
  2028. # #self.shell.append_error(''.join(traceback.format_exc()))
  2029. # #self.shell.append_error("?\n")
  2030. # self.shell.append_error(str(e) + "\n")
  2031. def info(self, msg):
  2032. """
  2033. Informs the user. Normally on the status bar, optionally
  2034. also on the shell.
  2035. :param msg: Text to write.
  2036. :return: None
  2037. """
  2038. # Type of message in brackets at the begining of the message.
  2039. match = re.search("\[([^\]]+)\](.*)", msg)
  2040. if match:
  2041. level = match.group(1)
  2042. msg_ = match.group(2)
  2043. self.ui.fcinfo.set_status(str(msg_), level=level)
  2044. if level.lower() == "error":
  2045. self.shell_message(msg, error=True, show=True)
  2046. elif level.lower() == "warning":
  2047. self.shell_message(msg, warning=True, show=True)
  2048. elif level.lower() == "error_notcl":
  2049. self.shell_message(msg, error=True, show=False)
  2050. elif level.lower() == "warning_notcl":
  2051. self.shell_message(msg, warning=True, show=False)
  2052. elif level.lower() == "success":
  2053. self.shell_message(msg, success=True, show=False)
  2054. elif level.lower() == "selected":
  2055. self.shell_message(msg, selected=True, show=False)
  2056. else:
  2057. self.shell_message(msg, show=False)
  2058. else:
  2059. self.ui.fcinfo.set_status(str(msg), level="info")
  2060. # make sure that if the message is to clear the infobar with a space
  2061. # is not printed over and over on the shell
  2062. if msg != '':
  2063. self.shell_message(msg)
  2064. def restore_toolbar_view(self):
  2065. tb = self.defaults["global_toolbar_view"]
  2066. if tb & 1:
  2067. self.ui.toolbarfile.setVisible(True)
  2068. else:
  2069. self.ui.toolbarfile.setVisible(False)
  2070. if tb & 2:
  2071. self.ui.toolbargeo.setVisible(True)
  2072. else:
  2073. self.ui.toolbargeo.setVisible(False)
  2074. if tb & 4:
  2075. self.ui.toolbarview.setVisible(True)
  2076. else:
  2077. self.ui.toolbarview.setVisible(False)
  2078. if tb & 8:
  2079. self.ui.toolbartools.setVisible(True)
  2080. else:
  2081. self.ui.toolbartools.setVisible(False)
  2082. if tb & 16:
  2083. self.ui.exc_edit_toolbar.setVisible(True)
  2084. else:
  2085. self.ui.exc_edit_toolbar.setVisible(False)
  2086. if tb & 32:
  2087. self.ui.geo_edit_toolbar.setVisible(True)
  2088. else:
  2089. self.ui.geo_edit_toolbar.setVisible(False)
  2090. if tb & 64:
  2091. self.ui.grb_edit_toolbar.setVisible(True)
  2092. else:
  2093. self.ui.grb_edit_toolbar.setVisible(False)
  2094. if tb & 128:
  2095. self.ui.snap_toolbar.setVisible(True)
  2096. else:
  2097. self.ui.snap_toolbar.setVisible(False)
  2098. if tb & 256:
  2099. self.ui.toolbarshell.setVisible(True)
  2100. else:
  2101. self.ui.toolbarshell.setVisible(False)
  2102. def load_defaults(self, filename):
  2103. """
  2104. Loads the aplication's default settings from current_defaults.FlatConfig into
  2105. ``self.defaults``.
  2106. :return: None
  2107. """
  2108. try:
  2109. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2110. options = f.read()
  2111. f.close()
  2112. except IOError:
  2113. self.log.error("Could not load defaults file.")
  2114. self.inform.emit(_("[ERROR] Could not load defaults file."))
  2115. # in case the defaults file can't be loaded, show all toolbars
  2116. self.defaults["global_toolbar_view"] = 511
  2117. return
  2118. try:
  2119. defaults = json.loads(options)
  2120. except:
  2121. # in case the defaults file can't be loaded, show all toolbars
  2122. self.defaults["global_toolbar_view"] = 511
  2123. e = sys.exc_info()[0]
  2124. App.log.error(str(e))
  2125. self.inform.emit(_("[ERROR] Failed to parse defaults file."))
  2126. return
  2127. self.defaults.update(defaults)
  2128. log.debug("FlatCAM defaults loaded from: %s" % filename)
  2129. # restore the toolbar view
  2130. self.restore_toolbar_view()
  2131. def on_import_preferences(self):
  2132. """
  2133. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  2134. ``self.defaults``.
  2135. :return: None
  2136. """
  2137. self.report_usage("on_import_preferences")
  2138. App.log.debug("on_import_preferences()")
  2139. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2140. try:
  2141. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2142. directory=self.data_path, filter=filter)
  2143. except TypeError:
  2144. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"), filter=filter)
  2145. filename = str(filename)
  2146. if filename == "":
  2147. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences import cancelled."))
  2148. else:
  2149. try:
  2150. f = open(filename)
  2151. options = f.read()
  2152. f.close()
  2153. except IOError:
  2154. self.log.error("Could not load defaults file.")
  2155. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2156. return
  2157. try:
  2158. defaults_from_file = json.loads(options)
  2159. except:
  2160. e = sys.exc_info()[0]
  2161. App.log.error(str(e))
  2162. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2163. return
  2164. self.defaults.update(defaults_from_file)
  2165. self.inform.emit(_("[success] Imported Defaults from %s") %filename)
  2166. def on_export_preferences(self):
  2167. self.report_usage("on_export_preferences")
  2168. App.log.debug("on_export_preferences()")
  2169. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  2170. try:
  2171. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  2172. caption=_("Export FlatCAM Preferences"),
  2173. directory=self.data_path + '/preferences_' + self.date, filter=filter
  2174. )
  2175. except TypeError:
  2176. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"), filter=filter)
  2177. filename = str(filename)
  2178. defaults_from_file = {}
  2179. if filename == "":
  2180. self.inform.emit(_("[WARNING_NOTCL] FlatCAM preferences export cancelled."))
  2181. return
  2182. else:
  2183. try:
  2184. f = open(filename, 'w')
  2185. defaults_file_content = f.read()
  2186. f.close()
  2187. except IOError:
  2188. App.log.debug('Creating a new preferences file ...')
  2189. f = open(filename, 'w')
  2190. json.dump({}, f)
  2191. f.close()
  2192. except:
  2193. e = sys.exc_info()[0]
  2194. App.log.error("Could not load defaults file.")
  2195. App.log.error(str(e))
  2196. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2197. return
  2198. try:
  2199. defaults_from_file = json.loads(defaults_file_content)
  2200. except:
  2201. App.log.warning("Trying to read an empty Preferences file. Continue.")
  2202. # Update options
  2203. self.defaults_read_form()
  2204. defaults_from_file.update(self.defaults)
  2205. self.propagate_defaults(silent=True)
  2206. # Save update options
  2207. try:
  2208. f = open(filename, "w")
  2209. json.dump(defaults_from_file, f)
  2210. f.close()
  2211. except:
  2212. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2213. return
  2214. self.file_saved.emit("preferences", filename)
  2215. self.inform.emit("[success] Exported Defaults to %s" % filename)
  2216. def on_preferences_open_folder(self):
  2217. self.report_usage("on_preferences_open_folder()")
  2218. if sys.platform == 'win32':
  2219. subprocess.Popen('explorer %s' % self.data_path)
  2220. elif sys.platform == 'darwin':
  2221. os.system('open "%s"' % self.data_path)
  2222. else:
  2223. subprocess.Popen(['xdg-open', self.data_path])
  2224. self.inform.emit("[success] FlatCAM Preferences Folder opened.")
  2225. def save_geometry(self, x, y, width, height, notebook_width):
  2226. self.defaults["global_def_win_x"] = x
  2227. self.defaults["global_def_win_y"] = y
  2228. self.defaults["global_def_win_w"] = width
  2229. self.defaults["global_def_win_h"] = height
  2230. self.defaults["global_def_notebook_width"] = notebook_width
  2231. self.save_defaults()
  2232. def message_dialog(self, title, message, kind="info"):
  2233. icon = {"info": QtWidgets.QMessageBox.Information,
  2234. "warning": QtWidgets.QMessageBox.Warning,
  2235. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2236. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2237. dlg.setText(message)
  2238. dlg.exec_()
  2239. def register_recent(self, kind, filename):
  2240. self.log.debug("register_recent()")
  2241. self.log.debug(" %s" % kind)
  2242. self.log.debug(" %s" % filename)
  2243. record = {'kind': str(kind), 'filename': str(filename)}
  2244. if record in self.recent:
  2245. return
  2246. self.recent.insert(0, record)
  2247. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2248. self.recent.pop()
  2249. try:
  2250. f = open(self.data_path + '/recent.json', 'w')
  2251. except IOError:
  2252. App.log.error("Failed to open recent items file for writing.")
  2253. self.inform.emit(_('[ERROR_NOTCL] Failed to open recent files file for writing.'))
  2254. return
  2255. #try:
  2256. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2257. # except:
  2258. # App.log.error("Failed to write to recent items file.")
  2259. # self.inform.emit('ERROR: Failed to write to recent items file.')
  2260. # f.close()
  2261. f.close()
  2262. # Re-buid the recent items menu
  2263. self.setup_recent_items()
  2264. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2265. """
  2266. Creates a new specalized FlatCAMObj and attaches it to the application,
  2267. this is, updates the GUI accordingly, any other records and plots it.
  2268. This method is thread-safe.
  2269. Notes:
  2270. * If the name is in use, the self.collection will modify it
  2271. when appending it to the collection. There is no need to handle
  2272. name conflicts here.
  2273. :param kind: The kind of object to create. One of 'gerber',
  2274. 'excellon', 'cncjob' and 'geometry'.
  2275. :type kind: str
  2276. :param name: Name for the object.
  2277. :type name: str
  2278. :param initialize: Function to run after creation of the object
  2279. but before it is attached to the application. The function is
  2280. called with 2 parameters: the new object and the App instance.
  2281. :type initialize: function
  2282. :return: None
  2283. :rtype: None
  2284. """
  2285. App.log.debug("new_object()")
  2286. obj_plot = plot
  2287. obj_autoselected = autoselected
  2288. t0 = time.time() # Debug
  2289. ## Create object
  2290. classdict = {
  2291. "gerber": FlatCAMGerber,
  2292. "excellon": FlatCAMExcellon,
  2293. "cncjob": FlatCAMCNCjob,
  2294. "geometry": FlatCAMGeometry
  2295. }
  2296. App.log.debug("Calling object constructor...")
  2297. obj = classdict[kind](name)
  2298. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  2299. # Set options from "Project options" form
  2300. self.options_read_form()
  2301. # IMPORTANT
  2302. # The key names in defaults and options dictionary's are not random:
  2303. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2304. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  2305. # the options from project options form into the self.options. After that, below, depending on the type of
  2306. # object that is created, it will strip the name of the object and the underline (if the original key was
  2307. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2308. # "toolchange"
  2309. for option in self.options:
  2310. if option.find(kind + "_") == 0:
  2311. oname = option[len(kind) + 1:]
  2312. obj.options[oname] = self.options[option]
  2313. obj.isHovering = False
  2314. obj.notHovering = True
  2315. # Initialize as per user request
  2316. # User must take care to implement initialize
  2317. # in a thread-safe way as is is likely that we
  2318. # have been invoked in a separate thread.
  2319. t1 = time.time()
  2320. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2321. try:
  2322. return_value = initialize(obj, self)
  2323. except Exception as e:
  2324. msg = _("[ERROR_NOTCL] An internal error has ocurred. See shell.\n")
  2325. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2326. msg += traceback.format_exc()
  2327. self.inform.emit(msg)
  2328. # if str(e) == "Empty Geometry":
  2329. # self.inform.emit("[ERROR_NOTCL] )
  2330. # else:
  2331. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2332. return "fail"
  2333. t2 = time.time()
  2334. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2335. if return_value == 'fail':
  2336. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2337. return "fail"
  2338. # Check units and convert if necessary
  2339. # This condition CAN be true because initialize() can change obj.units
  2340. if self.options["units"].upper() != obj.units.upper():
  2341. self.inform.emit(_("Converting units to ") + self.options["units"] + ".")
  2342. obj.convert_units(self.options["units"])
  2343. t3 = time.time()
  2344. self.log.debug("%f seconds converting units." % (t3 - t2))
  2345. # Create the bounding box for the object and then add the results to the obj.options
  2346. try:
  2347. xmin, ymin, xmax, ymax = obj.bounds()
  2348. obj.options['xmin'] = xmin
  2349. obj.options['ymin'] = ymin
  2350. obj.options['xmax'] = xmax
  2351. obj.options['ymax'] = ymax
  2352. except:
  2353. log.warning("The object has no bounds properties.")
  2354. # don't plot objects with no bounds, there is nothing to plot
  2355. self.plot = False
  2356. pass
  2357. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2358. # Move the object to the main thread and let the app know that it is available.
  2359. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2360. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2361. return obj
  2362. def new_excellon_object(self):
  2363. self.report_usage("new_excellon_object()")
  2364. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2365. def new_geometry_object(self):
  2366. self.report_usage("new_geometry_object()")
  2367. def initialize(obj, self):
  2368. obj.multitool = False
  2369. self.new_object('geometry', 'new_g', initialize, plot=False)
  2370. def on_object_created(self, obj, plot, autoselect):
  2371. """
  2372. Event callback for object creation.
  2373. :param obj: The newly created FlatCAM object.
  2374. :return: None
  2375. """
  2376. t0 = time.time() # DEBUG
  2377. self.log.debug("on_object_created()")
  2378. # The Collection might change the name if there is a collision
  2379. self.collection.append(obj)
  2380. # after adding the object to the collection always update the list of objects that are in the collection
  2381. self.all_objects_list = self.collection.get_list()
  2382. # self.inform.emit('[selected] %s created & selected: %s' %
  2383. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2384. if obj.kind == 'gerber':
  2385. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2386. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  2387. elif obj.kind == 'excellon':
  2388. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2389. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  2390. elif obj.kind == 'cncjob':
  2391. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2392. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  2393. elif obj.kind == 'geometry':
  2394. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  2395. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  2396. # update the SHELL auto-completer model with the name of the new object
  2397. self.myKeywords.append(obj.options['name'])
  2398. self.shell._edit.set_model_data(self.myKeywords)
  2399. self.ui.code_editor.set_model_data(self.myKeywords)
  2400. if autoselect:
  2401. # select the just opened object but deselect the previous ones
  2402. self.collection.set_all_inactive()
  2403. self.collection.set_active(obj.options["name"])
  2404. # here it is done the object plotting
  2405. def worker_task(obj):
  2406. with self.proc_container.new("Plotting"):
  2407. if isinstance(obj, FlatCAMCNCjob):
  2408. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2409. else:
  2410. obj.plot()
  2411. t1 = time.time() # DEBUG
  2412. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2413. self.object_plotted.emit(obj)
  2414. # Send to worker
  2415. # self.worker.add_task(worker_task, [self])
  2416. if plot is True:
  2417. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2418. def on_object_changed(self, obj):
  2419. # update the bounding box data from obj.options
  2420. xmin, ymin, xmax, ymax = obj.bounds()
  2421. obj.options['xmin'] = xmin
  2422. obj.options['ymin'] = ymin
  2423. obj.options['xmax'] = xmax
  2424. obj.options['ymax'] = ymax
  2425. log.debug("Object changed, updating the bounding box data on self.options")
  2426. # delete the old selection shape
  2427. self.delete_selection_shape()
  2428. self.should_we_save = True
  2429. def on_object_plotted(self, obj):
  2430. self.on_zoom_fit(None)
  2431. def options_read_form(self):
  2432. for option in self.options_form_fields:
  2433. self.options[option] = self.options_form_fields[option].get_value()
  2434. def options_write_form(self):
  2435. for option in self.options:
  2436. self.options_write_form_field(option)
  2437. def options_write_form_field(self, field):
  2438. try:
  2439. self.options_form_fields[field].set_value(self.options[field])
  2440. except KeyError:
  2441. # Changed from error to debug. This allows to have data stored
  2442. # which is not user-editable.
  2443. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2444. pass
  2445. def on_about(self):
  2446. """
  2447. Displays the "about" dialog.
  2448. :return: None
  2449. """
  2450. self.report_usage("on_about")
  2451. version = self.version
  2452. version_date = self.version_date
  2453. beta = self.beta
  2454. class AboutDialog(QtWidgets.QDialog):
  2455. def __init__(self, parent=None):
  2456. QtWidgets.QDialog.__init__(self, parent)
  2457. # Icon and title
  2458. self.setWindowIcon(parent.app_icon)
  2459. self.setWindowTitle("FlatCAM")
  2460. layout1 = QtWidgets.QVBoxLayout()
  2461. self.setLayout(layout1)
  2462. layout2 = QtWidgets.QHBoxLayout()
  2463. layout1.addLayout(layout2)
  2464. logo = QtWidgets.QLabel()
  2465. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2466. layout2.addWidget(logo, stretch=0)
  2467. title = QtWidgets.QLabel(
  2468. _(
  2469. "<font size=8><B>FlatCAM</B></font><BR>"
  2470. "Version {version} {beta} ({date}) - {arch} <BR>"
  2471. "<BR>"
  2472. "2D Computer-Aided Printed Circuit Board<BR>"
  2473. "Manufacturing.<BR>"
  2474. "<BR>"
  2475. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2476. "<BR>"
  2477. "<B> Main Contributors:</B><BR>"
  2478. "Denis Hayrullin<BR>"
  2479. "Kamil Sopko<BR>"
  2480. "Marius Stanciu<BR>"
  2481. "Matthieu Berthomé<BR>"
  2482. "and many others found "
  2483. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2484. "<BR>"
  2485. "Development is done "
  2486. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2487. "DOWNLOAD area "
  2488. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2489. ""
  2490. ).format(version=version,
  2491. beta=('BETA' if beta else ''),
  2492. date=version_date,
  2493. arch=platform.architecture()[0])
  2494. )
  2495. title.setOpenExternalLinks(True)
  2496. layout2.addWidget(title, stretch=1)
  2497. layout3 = QtWidgets.QHBoxLayout()
  2498. layout1.addLayout(layout3)
  2499. layout3.addStretch()
  2500. okbtn = QtWidgets.QPushButton("Close")
  2501. layout3.addWidget(okbtn)
  2502. okbtn.clicked.connect(self.accept)
  2503. AboutDialog(self.ui).exec_()
  2504. def on_file_savedefaults(self):
  2505. """
  2506. Callback for menu item File->Save Defaults. Saves application default options
  2507. ``self.defaults`` to current_defaults.FlatConfig.
  2508. :return: None
  2509. """
  2510. self.save_defaults()
  2511. # def on_app_exit(self):
  2512. # self.report_usage("on_app_exit()")
  2513. #
  2514. # if self.collection.get_list():
  2515. # msgbox = QtWidgets.QMessageBox()
  2516. # # msgbox.setText("<B>Save changes ...</B>")
  2517. # msgbox.setText("There are files/objects opened in FlatCAM. "
  2518. # "\n"
  2519. # "Do you want to Save the project?")
  2520. # msgbox.setWindowTitle("Save changes")
  2521. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2522. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2523. # QtWidgets.QMessageBox.Cancel)
  2524. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2525. #
  2526. # response = msgbox.exec_()
  2527. #
  2528. # if response == QtWidgets.QMessageBox.Yes:
  2529. # self.on_file_saveprojectas(thread=False)
  2530. # elif response == QtWidgets.QMessageBox.Cancel:
  2531. # return
  2532. # self.save_defaults()
  2533. # else:
  2534. # self.save_defaults()
  2535. # log.debug("Application defaults saved ... Exit event.")
  2536. # QtWidgets.qApp.quit()
  2537. def save_defaults(self, silent=False):
  2538. """
  2539. Saves application default options
  2540. ``self.defaults`` to current_defaults.FlatConfig.
  2541. :return: None
  2542. """
  2543. self.report_usage("save_defaults")
  2544. # Read options from file
  2545. try:
  2546. f = open(self.data_path + "/current_defaults.FlatConfig")
  2547. defaults_file_content = f.read()
  2548. f.close()
  2549. except:
  2550. e = sys.exc_info()[0]
  2551. App.log.error("Could not load defaults file.")
  2552. App.log.error(str(e))
  2553. self.inform.emit(_("[ERROR_NOTCL] Could not load defaults file."))
  2554. return
  2555. try:
  2556. defaults = json.loads(defaults_file_content)
  2557. except:
  2558. e = sys.exc_info()[0]
  2559. App.log.error("Failed to parse defaults file.")
  2560. App.log.error(str(e))
  2561. self.inform.emit(_("[ERROR_NOTCL] Failed to parse defaults file."))
  2562. return
  2563. # Update options
  2564. self.defaults_read_form()
  2565. defaults.update(self.defaults)
  2566. self.propagate_defaults(silent=True)
  2567. # Save the toolbar view
  2568. tb_status = 0
  2569. if self.ui.toolbarfile.isVisible():
  2570. tb_status += 1
  2571. if self.ui.toolbargeo.isVisible():
  2572. tb_status += 2
  2573. if self.ui.toolbarview.isVisible():
  2574. tb_status += 4
  2575. if self.ui.toolbartools.isVisible():
  2576. tb_status += 8
  2577. if self.ui.exc_edit_toolbar.isVisible():
  2578. tb_status += 16
  2579. if self.ui.geo_edit_toolbar.isVisible():
  2580. tb_status += 32
  2581. if self.ui.grb_edit_toolbar.isVisible():
  2582. tb_status += 64
  2583. if self.ui.snap_toolbar.isVisible():
  2584. tb_status += 128
  2585. if self.ui.toolbarshell.isVisible():
  2586. tb_status += 256
  2587. self.defaults["global_toolbar_view"] = tb_status
  2588. # Save update options
  2589. try:
  2590. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2591. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2592. f.close()
  2593. except:
  2594. self.inform.emit(_("[ERROR_NOTCL] Failed to write defaults to file."))
  2595. return
  2596. if not silent:
  2597. self.inform.emit(_("[success] Defaults saved."))
  2598. def save_factory_defaults(self, silent=False):
  2599. """
  2600. Saves application factory default options
  2601. ``self.defaults`` to factory_defaults.FlatConfig.
  2602. It's a one time job done just after the first install.
  2603. :return: None
  2604. """
  2605. self.report_usage("save_factory_defaults")
  2606. # Read options from file
  2607. try:
  2608. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2609. factory_defaults_file_content = f_f_def.read()
  2610. f_f_def.close()
  2611. except:
  2612. e = sys.exc_info()[0]
  2613. App.log.error("Could not load factory defaults file.")
  2614. App.log.error(str(e))
  2615. self.inform.emit(_("[ERROR_NOTCL] Could not load factory defaults file."))
  2616. return
  2617. try:
  2618. factory_defaults = json.loads(factory_defaults_file_content)
  2619. except:
  2620. e = sys.exc_info()[0]
  2621. App.log.error("Failed to parse factory defaults file.")
  2622. App.log.error(str(e))
  2623. self.inform.emit(_("[ERROR_NOTCL] Failed to parse factory defaults file."))
  2624. return
  2625. # Update options
  2626. self.defaults_read_form()
  2627. factory_defaults.update(self.defaults)
  2628. self.propagate_defaults(silent=True)
  2629. # Save update options
  2630. try:
  2631. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2632. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2633. f_f_def_s.close()
  2634. except:
  2635. self.inform.emit(_("[ERROR_NOTCL] Failed to write factory defaults to file."))
  2636. return
  2637. if silent is False:
  2638. self.inform.emit(_("Factory defaults saved."))
  2639. def final_save(self):
  2640. if self.save_in_progress:
  2641. self.inform.emit(_("Application is saving the project. Please wait ..."))
  2642. return
  2643. if self.should_we_save and self.collection.get_list():
  2644. msgbox = QtWidgets.QMessageBox()
  2645. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2646. "\n"
  2647. "Do you want to Save the project?"))
  2648. msgbox.setWindowTitle(_("Save changes"))
  2649. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2650. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2651. QtWidgets.QMessageBox.Cancel)
  2652. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2653. response = msgbox.exec_()
  2654. if response == QtWidgets.QMessageBox.Yes:
  2655. self.on_file_saveprojectas(thread=True, quit=True)
  2656. elif response == QtWidgets.QMessageBox.No:
  2657. self.quit_application()
  2658. elif response == QtWidgets.QMessageBox.Cancel:
  2659. return
  2660. else:
  2661. self.quit_application()
  2662. def quit_application(self):
  2663. self.save_defaults()
  2664. log.debug("App.final_save() --> App Defaults saved.")
  2665. # save toolbar state to file
  2666. settings = QSettings("Open Source", "FlatCAM")
  2667. settings.setValue('saved_gui_state', self.ui.saveState())
  2668. settings.setValue('maximized_gui', self.ui.isMaximized())
  2669. # This will write the setting to the platform specific storage.
  2670. del settings
  2671. log.debug("App.final_save() --> App UI state saved.")
  2672. QtWidgets.qApp.quit()
  2673. def on_toggle_shell(self):
  2674. """
  2675. toggle shell if is visible close it if closed open it
  2676. :return:
  2677. """
  2678. self.report_usage("on_toggle_shell()")
  2679. if self.ui.shell_dock.isVisible():
  2680. self.ui.shell_dock.hide()
  2681. else:
  2682. self.ui.shell_dock.show()
  2683. def on_edit_join(self, name=None):
  2684. """
  2685. Callback for Edit->Join. Joins the selected geometry objects into
  2686. a new one.
  2687. :return: None
  2688. """
  2689. self.report_usage("on_edit_join()")
  2690. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2691. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2692. tooldias = []
  2693. geo_type_list = []
  2694. objs = self.collection.get_selected()
  2695. for obj in objs:
  2696. geo_type_list.append(obj.multigeo)
  2697. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2698. if len(set(geo_type_list)) != 1:
  2699. self.inform.emit(_("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2700. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2701. "convert from one to another and retry joining \n"
  2702. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2703. "the result may not be what was expected. \n"
  2704. "Check the generated GCODE."))
  2705. return
  2706. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2707. if True in geo_type_list:
  2708. def initialize(obj, app):
  2709. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2710. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2711. for v in obj.tools.values():
  2712. v['data']['name'] = obj_name_multi
  2713. self.new_object("geometry", obj_name_multi, initialize)
  2714. else:
  2715. def initialize(obj, app):
  2716. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2717. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2718. for v in obj.tools.values():
  2719. v['data']['name'] = obj_name_single
  2720. self.new_object("geometry", obj_name_single, initialize)
  2721. self.should_we_save = True
  2722. def on_edit_join_exc(self):
  2723. """
  2724. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2725. a new one.
  2726. :return: None
  2727. """
  2728. self.report_usage("on_edit_join_exc()")
  2729. objs = self.collection.get_selected()
  2730. for obj in objs:
  2731. if not isinstance(obj, FlatCAMExcellon):
  2732. self.inform.emit(_("[ERROR_NOTCL] Failed. Excellon joining works only on Excellon objects."))
  2733. return
  2734. def initialize(obj, app):
  2735. FlatCAMExcellon.merge(objs, obj)
  2736. self.new_object("excellon", 'Combo_Excellon', initialize)
  2737. self.should_we_save = True
  2738. def on_edit_join_grb(self):
  2739. """
  2740. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2741. a new one.
  2742. :return: None
  2743. """
  2744. self.report_usage("on_edit_join_grb()")
  2745. objs = self.collection.get_selected()
  2746. for obj in objs:
  2747. if not isinstance(obj, FlatCAMGerber):
  2748. self.inform.emit(_("[ERROR_NOTCL] Failed. Gerber joining works only on Gerber objects."))
  2749. return
  2750. def initialize(obj, app):
  2751. FlatCAMGerber.merge(objs, obj)
  2752. self.new_object("gerber", 'Combo_Gerber', initialize)
  2753. self.should_we_save = True
  2754. def on_convert_singlegeo_to_multigeo(self):
  2755. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2756. obj = self.collection.get_active()
  2757. if obj is None:
  2758. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2759. return
  2760. if not isinstance(obj, FlatCAMGeometry):
  2761. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2762. return
  2763. obj.multigeo = True
  2764. for tooluid, dict_value in obj.tools.items():
  2765. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2766. if not isinstance(obj.solid_geometry, list):
  2767. obj.solid_geometry = [obj.solid_geometry]
  2768. obj.solid_geometry[:] = []
  2769. obj.plot()
  2770. self.should_we_save = True
  2771. self.inform.emit(_("[success] A Geometry object was converted to MultiGeo type."))
  2772. def on_convert_multigeo_to_singlegeo(self):
  2773. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2774. obj = self.collection.get_active()
  2775. if obj is None:
  2776. self.inform.emit(_("[ERROR_NOTCL] Failed. Select a Geometry Object and try again."))
  2777. return
  2778. if not isinstance(obj, FlatCAMGeometry):
  2779. self.inform.emit(_("[ERROR_NOTCL] Expected a FlatCAMGeometry, got %s") % type(obj))
  2780. return
  2781. obj.multigeo = False
  2782. total_solid_geometry = []
  2783. for tooluid, dict_value in obj.tools.items():
  2784. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2785. # clear the original geometry
  2786. dict_value['solid_geometry'][:] = []
  2787. obj.solid_geometry = deepcopy(total_solid_geometry)
  2788. obj.plot()
  2789. self.should_we_save = True
  2790. self.inform.emit(_("[success] A Geometry object was converted to SingleGeo type."))
  2791. def on_options_dict_change(self, field):
  2792. self.options_write_form_field(field)
  2793. if field == "units":
  2794. self.set_screen_units(self.options['units'])
  2795. def on_defaults_dict_change(self, field):
  2796. self.defaults_write_form_field(field)
  2797. if field == "units":
  2798. self.set_screen_units(self.defaults['units'])
  2799. def set_screen_units(self, units):
  2800. self.ui.units_label.setText("[" + self.defaults["units"].lower() + "]")
  2801. def on_toggle_units(self):
  2802. """
  2803. Callback for the Units radio-button change in the Options tab.
  2804. Changes the application's default units or the current project's units.
  2805. If changing the project's units, the change propagates to all of
  2806. the objects in the project.
  2807. :return: None
  2808. """
  2809. self.report_usage("on_toggle_units")
  2810. if self.toggle_units_ignore:
  2811. return
  2812. # If option is the same, then ignore
  2813. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == \
  2814. self.defaults["units"].upper():
  2815. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  2816. return
  2817. # Options to scale
  2818. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  2819. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  2820. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2821. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  2822. "excellon_z_pdepth",
  2823. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  2824. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  2825. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  2826. "geometry_feedrate_probe",
  2827. 'cncjob_tooldia',
  2828. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  2829. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin",
  2830. "tools_2sided_drilldia", "tools_film_boundary",
  2831. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2832. "tools_panelize_constrainx", "tools_panelize_constrainy",
  2833. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  2834. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  2835. "tools_transform_offset_y",
  2836. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  2837. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  2838. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  2839. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  2840. 'global_gridx', 'global_gridy', 'global_snap_max']
  2841. def scale_options(sfactor):
  2842. for dim in dimensions:
  2843. if dim == 'excellon_toolchangexy':
  2844. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2845. coords_xy[0] *= sfactor
  2846. coords_xy[1] *= sfactor
  2847. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2848. elif dim == 'geometry_toolchangexy':
  2849. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2850. coords_xy[0] *= sfactor
  2851. coords_xy[1] *= sfactor
  2852. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2853. elif dim == 'tools_ncctools':
  2854. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2855. ncctols[0] *= sfactor
  2856. ncctols[1] *= sfactor
  2857. self.options['tools_ncctools'] = "%f, %f" % (ncctols[0], ncctols[1])
  2858. elif dim == 'tools_solderpaste_tools':
  2859. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2860. sp_tools[0] *= sfactor
  2861. sp_tools[1] *= sfactor
  2862. self.options['tools_solderpaste_tools'] = "%f, %f" % (sp_tools[0], sp_tools[1])
  2863. elif dim == 'tools_solderpaste_xy_toolchange':
  2864. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2865. sp_coords[0] *= sfactor
  2866. sp_coords[1] *= sfactor
  2867. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  2868. else:
  2869. try:
  2870. self.options[dim] = float(self.options[dim]) * sfactor
  2871. except Exception as e:
  2872. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  2873. def scale_defaults(sfactor):
  2874. for dim in dimensions:
  2875. if dim == 'excellon_toolchangexy':
  2876. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2877. coords_xy[0] *= sfactor
  2878. coords_xy[1] *= sfactor
  2879. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2880. elif dim == 'geometry_toolchangexy':
  2881. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2882. coords_xy[0] *= sfactor
  2883. coords_xy[1] *= sfactor
  2884. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  2885. elif dim == 'tools_ncctools':
  2886. ncctols = [float(eval(a)) for a in self.defaults["tools_ncctools"].split(",")]
  2887. ncctols[0] *= sfactor
  2888. ncctols[1] *= sfactor
  2889. self.defaults['tools_ncctools'] = "%.4f, %.4f" % (ncctols[0], ncctols[1])
  2890. elif dim == 'tools_solderpaste_tools':
  2891. sp_tools = [float(eval(a)) for a in self.defaults["tools_solderpaste_tools"].split(",")]
  2892. sp_tools[0] *= sfactor
  2893. sp_tools[1] *= sfactor
  2894. self.defaults['tools_solderpaste_tools'] = "%.4f, %.4f" % (sp_tools[0], sp_tools[1])
  2895. elif dim == 'tools_solderpaste_xy_toolchange':
  2896. sp_coords = [float(eval(a)) for a in self.defaults["tools_solderpaste_xy_toolchange"].split(",")]
  2897. sp_coords[0] *= sfactor
  2898. sp_coords[1] *= sfactor
  2899. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  2900. else:
  2901. try:
  2902. self.defaults[dim] = float(self.defaults[dim]) * sfactor
  2903. except Exception as e:
  2904. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  2905. # The scaling factor depending on choice of units.
  2906. factor = 1/25.4
  2907. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2908. factor = 25.4
  2909. # Changing project units. Warn user.
  2910. msgbox = QtWidgets.QMessageBox()
  2911. msgbox.setWindowTitle("Toggle Units")
  2912. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  2913. msgbox.setText("<B>Change project units ...</B>")
  2914. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2915. "properties of all objects to be scaled accordingly.\nContinue?")
  2916. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2917. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2918. response = msgbox.exec_()
  2919. if response == QtWidgets.QMessageBox.Ok:
  2920. self.options_read_form()
  2921. scale_options(factor)
  2922. self.options_write_form()
  2923. self.defaults_read_form()
  2924. scale_defaults(factor)
  2925. self.defaults_write_form()
  2926. self.should_we_save = True
  2927. # change this only if the workspace is active
  2928. if self.defaults['global_workspace'] is True:
  2929. self.plotcanvas.draw_workspace()
  2930. # adjust the grid values on the main toolbar
  2931. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2932. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2933. for obj in self.collection.get_list():
  2934. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  2935. obj.convert_units(units)
  2936. # make that the properties stored in the object are also updated
  2937. self.object_changed.emit(obj)
  2938. obj.build_ui()
  2939. current = self.collection.get_active()
  2940. if current is not None:
  2941. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2942. if not isinstance(current, FlatCAMGeometry):
  2943. current.to_form()
  2944. self.plot_all()
  2945. self.inform.emit(_("[success] Converted units to %s") % self.defaults["units"])
  2946. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2947. self.set_screen_units(self.defaults["units"])
  2948. else:
  2949. # Undo toggling
  2950. self.toggle_units_ignore = True
  2951. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2952. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  2953. else:
  2954. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  2955. self.toggle_units_ignore = False
  2956. self.inform.emit(_("[WARNING_NOTCL] Units conversion cancelled."))
  2957. self.options_read_form()
  2958. self.defaults_read_form()
  2959. def on_toggle_units_click(self):
  2960. if self.options["units"] == 'MM':
  2961. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  2962. else:
  2963. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  2964. self.on_toggle_units()
  2965. def on_fullscreen(self):
  2966. self.report_usage("on_fullscreen()")
  2967. if self.toggle_fscreen is False:
  2968. if sys.platform == 'win32':
  2969. self.ui.showFullScreen()
  2970. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2971. tb.setVisible(False)
  2972. self.ui.splitter_left.setVisible(False)
  2973. self.toggle_fscreen = True
  2974. else:
  2975. if sys.platform == 'win32':
  2976. self.ui.showNormal()
  2977. self.restore_toolbar_view()
  2978. self.ui.splitter_left.setVisible(True)
  2979. self.toggle_fscreen = False
  2980. def on_toggle_plotarea(self):
  2981. self.report_usage("on_toggle_plotarea()")
  2982. try:
  2983. name = self.ui.plot_tab_area.widget(0).objectName()
  2984. except AttributeError:
  2985. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2986. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2987. self.ui.plot_tab_area.protectTab(0)
  2988. return
  2989. if name != 'plotarea':
  2990. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2991. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2992. self.ui.plot_tab_area.protectTab(0)
  2993. else:
  2994. self.ui.plot_tab_area.closeTab(0)
  2995. def on_toggle_notebook(self):
  2996. if self.ui.splitter.sizes()[0] == 0:
  2997. self.ui.splitter.setSizes([1, 1])
  2998. else:
  2999. self.ui.splitter.setSizes([0, 1])
  3000. def on_toggle_axis(self):
  3001. self.report_usage("on_toggle_axis()")
  3002. if self.toggle_axis is False:
  3003. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3004. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  3005. self.plotcanvas.redraw()
  3006. self.toggle_axis = True
  3007. else:
  3008. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3009. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  3010. self.plotcanvas.redraw()
  3011. self.toggle_axis = False
  3012. def on_toggle_grid(self):
  3013. self.report_usage("on_toggle_grid()")
  3014. self.ui.grid_snap_btn.trigger()
  3015. def on_options_combo_change(self, sel):
  3016. """
  3017. Called when the combo box to choose between application defaults and
  3018. project option changes value. The corresponding variables are
  3019. copied to the UI.
  3020. :param sel: The option index that was chosen.
  3021. :return: None
  3022. """
  3023. # combo_sel = self.ui.notebook.combo_options.get_active()
  3024. App.log.debug("Options --> %s" % sel)
  3025. # form = [self.defaults_form, self.options_form][sel]
  3026. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  3027. if sel == 0:
  3028. self.gen_form = self.ui.general_defaults_form
  3029. self.ger_form = self.ui.gerber_defaults_form
  3030. self.exc_form = self.ui.excellon_defaults_form
  3031. self.geo_form = self.ui.geometry_defaults_form
  3032. self.cnc_form = self.ui.cncjob_defaults_form
  3033. self.tools_form = self.ui.tools_defaults_form
  3034. elif sel == 1:
  3035. self.gen_form = self.ui.general_options_form
  3036. self.ger_form = self.ui.gerber_options_form
  3037. self.exc_form = self.ui.excellon_options_form
  3038. self.geo_form = self.ui.geometry_options_form
  3039. self.cnc_form = self.ui.cncjob_options_form
  3040. self.tools_form = self.ui.tools_options_form
  3041. else:
  3042. return
  3043. try:
  3044. self.ui.general_scroll_area.takeWidget()
  3045. except:
  3046. self.log.debug("Nothing to remove")
  3047. self.ui.general_scroll_area.setWidget(self.gen_form)
  3048. self.gen_form.show()
  3049. try:
  3050. self.ui.gerber_scroll_area.takeWidget()
  3051. except:
  3052. self.log.debug("Nothing to remove")
  3053. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  3054. self.ger_form.show()
  3055. try:
  3056. self.ui.excellon_scroll_area.takeWidget()
  3057. except:
  3058. self.log.debug("Nothing to remove")
  3059. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  3060. self.exc_form.show()
  3061. try:
  3062. self.ui.geometry_scroll_area.takeWidget()
  3063. except:
  3064. self.log.debug("Nothing to remove")
  3065. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  3066. self.geo_form.show()
  3067. try:
  3068. self.ui.cncjob_scroll_area.takeWidget()
  3069. except:
  3070. self.log.debug("Nothing to remove")
  3071. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  3072. self.cnc_form.show()
  3073. try:
  3074. self.ui.tools_scroll_area.takeWidget()
  3075. except:
  3076. self.log.debug("Nothing to remove")
  3077. self.ui.tools_scroll_area.setWidget(self.tools_form)
  3078. self.tools_form.show()
  3079. self.log.debug("Finished GUI form initialization.")
  3080. # self.options2form()
  3081. def on_excellon_defaults_button(self):
  3082. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  3083. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  3084. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  3085. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  3086. self.defaults_form_fields["excellon_zeros"].set_value('L')
  3087. self.defaults_form_fields["excellon_units"].set_value('INCH')
  3088. log.debug("Excellon app defaults loaded ...")
  3089. def on_excellon_options_button(self):
  3090. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  3091. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  3092. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  3093. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  3094. self.options_form_fields["excellon_zeros"].set_value('L')
  3095. self.options_form_fields["excellon_units"].set_value('INCH')
  3096. log.debug("Excellon options defaults loaded ...")
  3097. # Setting plot colors handlers
  3098. def on_pf_color_entry(self):
  3099. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  3100. self.defaults['global_plot_fill'][7:9]
  3101. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3102. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  3103. def on_pf_color_button(self):
  3104. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  3105. c_dialog = QtWidgets.QColorDialog()
  3106. plot_fill_color = c_dialog.getColor(initial=current_color)
  3107. if plot_fill_color.isValid() is False:
  3108. return
  3109. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  3110. "background-color:%s" % str(plot_fill_color.name()))
  3111. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  3112. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  3113. self.defaults['global_plot_fill'] = new_val
  3114. def on_pf_color_spinner(self):
  3115. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  3116. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  3117. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  3118. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3119. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  3120. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3121. def on_pf_color_slider(self):
  3122. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  3123. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  3124. def on_pl_color_entry(self):
  3125. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  3126. self.defaults['global_plot_line'][7:9]
  3127. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3128. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  3129. def on_pl_color_button(self):
  3130. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  3131. # print(current_color)
  3132. c_dialog = QtWidgets.QColorDialog()
  3133. plot_line_color = c_dialog.getColor(initial=current_color)
  3134. if plot_line_color.isValid() is False:
  3135. return
  3136. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  3137. "background-color:%s" % str(plot_line_color.name()))
  3138. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  3139. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  3140. self.defaults['global_plot_line'] = new_val_line
  3141. # Setting selection colors (left - right) handlers
  3142. def on_sf_color_entry(self):
  3143. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  3144. self.defaults['global_sel_fill'][7:9]
  3145. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3146. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  3147. def on_sf_color_button(self):
  3148. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  3149. c_dialog = QtWidgets.QColorDialog()
  3150. plot_fill_color = c_dialog.getColor(initial=current_color)
  3151. if plot_fill_color.isValid() is False:
  3152. return
  3153. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  3154. "background-color:%s" % str(plot_fill_color.name()))
  3155. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  3156. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  3157. self.defaults['global_sel_fill'] = new_val
  3158. def on_sf_color_spinner(self):
  3159. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  3160. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  3161. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  3162. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3163. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  3164. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3165. def on_sf_color_slider(self):
  3166. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  3167. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  3168. def on_sl_color_entry(self):
  3169. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  3170. self.defaults['global_sel_line'][7:9]
  3171. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3172. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  3173. def on_sl_color_button(self):
  3174. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  3175. c_dialog = QtWidgets.QColorDialog()
  3176. plot_line_color = c_dialog.getColor(initial=current_color)
  3177. if plot_line_color.isValid() is False:
  3178. return
  3179. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  3180. "background-color:%s" % str(plot_line_color.name()))
  3181. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  3182. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  3183. self.defaults['global_sel_line'] = new_val_line
  3184. # Setting selection colors (right - left) handlers
  3185. def on_alt_sf_color_entry(self):
  3186. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  3187. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  3188. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3189. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  3190. def on_alt_sf_color_button(self):
  3191. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  3192. c_dialog = QtWidgets.QColorDialog()
  3193. plot_fill_color = c_dialog.getColor(initial=current_color)
  3194. if plot_fill_color.isValid() is False:
  3195. return
  3196. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  3197. "background-color:%s" % str(plot_fill_color.name()))
  3198. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  3199. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  3200. self.defaults['global_alt_sel_fill'] = new_val
  3201. def on_alt_sf_color_spinner(self):
  3202. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  3203. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  3204. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  3205. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3206. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  3207. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  3208. def on_alt_sf_color_slider(self):
  3209. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  3210. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  3211. def on_alt_sl_color_entry(self):
  3212. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  3213. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  3214. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3215. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  3216. def on_alt_sl_color_button(self):
  3217. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  3218. c_dialog = QtWidgets.QColorDialog()
  3219. plot_line_color = c_dialog.getColor(initial=current_color)
  3220. if plot_line_color.isValid() is False:
  3221. return
  3222. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  3223. "background-color:%s" % str(plot_line_color.name()))
  3224. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  3225. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  3226. self.defaults['global_alt_sel_line'] = new_val_line
  3227. # Setting Editor colors
  3228. def on_draw_color_entry(self):
  3229. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3230. .draw_color_entry.get_value()
  3231. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3232. "background-color:%s" % str(self.defaults['global_draw_color']))
  3233. def on_draw_color_button(self):
  3234. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  3235. c_dialog = QtWidgets.QColorDialog()
  3236. draw_color = c_dialog.getColor(initial=current_color)
  3237. if draw_color.isValid() is False:
  3238. return
  3239. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  3240. "background-color:%s" % str(draw_color.name()))
  3241. new_val = str(draw_color.name())
  3242. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  3243. self.defaults['global_draw_color'] = new_val
  3244. def on_sel_draw_color_entry(self):
  3245. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  3246. .sel_draw_color_entry.get_value()
  3247. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3248. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  3249. def on_sel_draw_color_button(self):
  3250. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  3251. c_dialog = QtWidgets.QColorDialog()
  3252. sel_draw_color = c_dialog.getColor(initial=current_color)
  3253. if sel_draw_color.isValid() is False:
  3254. return
  3255. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  3256. "background-color:%s" % str(sel_draw_color.name()))
  3257. new_val_sel = str(sel_draw_color.name())
  3258. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  3259. self.defaults['global_sel_draw_color'] = new_val_sel
  3260. def on_deselect_all(self):
  3261. self.collection.set_all_inactive()
  3262. self.delete_selection_shape()
  3263. def on_workspace_modified(self):
  3264. self.save_defaults(silent=True)
  3265. self.plotcanvas.draw_workspace()
  3266. def on_workspace(self):
  3267. self.report_usage("on_workspace()")
  3268. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3269. self.plotcanvas.restore_workspace()
  3270. else:
  3271. self.plotcanvas.delete_workspace()
  3272. self.save_defaults(silent=True)
  3273. def on_workspace_menu(self):
  3274. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  3275. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  3276. else:
  3277. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  3278. self.on_workspace()
  3279. def on_layout(self, index, lay=None):
  3280. self.report_usage("on_layout()")
  3281. if lay:
  3282. current_layout = lay
  3283. else:
  3284. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  3285. settings = QSettings("Open Source", "FlatCAM")
  3286. settings.setValue('layout', current_layout)
  3287. # This will write the setting to the platform specific storage.
  3288. del settings
  3289. # first remove the toolbars:
  3290. try:
  3291. self.ui.removeToolBar(self.ui.toolbarfile)
  3292. self.ui.removeToolBar(self.ui.toolbargeo)
  3293. self.ui.removeToolBar(self.ui.toolbarview)
  3294. self.ui.removeToolBar(self.ui.toolbarshell)
  3295. self.ui.removeToolBar(self.ui.toolbartools)
  3296. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  3297. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  3298. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  3299. self.ui.removeToolBar(self.ui.snap_toolbar)
  3300. self.ui.removeToolBar(self.ui.toolbarshell)
  3301. except:
  3302. pass
  3303. if current_layout == 'standard':
  3304. ### TOOLBAR INSTALLATION ###
  3305. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3306. self.ui.toolbarfile.setObjectName('File_TB')
  3307. self.ui.addToolBar(self.ui.toolbarfile)
  3308. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3309. self.ui.toolbargeo.setObjectName('Edit_TB')
  3310. self.ui.addToolBar(self.ui.toolbargeo)
  3311. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3312. self.ui.toolbarview.setObjectName('View_TB')
  3313. self.ui.addToolBar(self.ui.toolbarview)
  3314. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3315. self.ui.toolbarshell.setObjectName('Shell_TB')
  3316. self.ui.addToolBar(self.ui.toolbarshell)
  3317. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3318. self.ui.toolbartools.setObjectName('Tools_TB')
  3319. self.ui.addToolBar(self.ui.toolbartools)
  3320. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3321. self.ui.exc_edit_toolbar.setVisible(False)
  3322. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3323. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  3324. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3325. self.ui.geo_edit_toolbar.setVisible(False)
  3326. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3327. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  3328. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3329. self.ui.grb_edit_toolbar.setVisible(False)
  3330. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3331. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  3332. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3333. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3334. # self.ui.snap_toolbar.setMaximumHeight(30)
  3335. self.ui.addToolBar(self.ui.snap_toolbar)
  3336. self.ui.corner_snap_btn.setVisible(False)
  3337. self.ui.snap_magnet.setVisible(False)
  3338. elif current_layout == 'compact':
  3339. ### TOOLBAR INSTALLATION ###
  3340. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  3341. self.ui.toolbarfile.setObjectName('File_TB')
  3342. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  3343. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  3344. self.ui.toolbargeo.setObjectName('Edit_TB')
  3345. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  3346. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  3347. self.ui.toolbarview.setObjectName('View_TB')
  3348. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  3349. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  3350. self.ui.toolbarshell.setObjectName('Shell_TB')
  3351. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  3352. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  3353. self.ui.toolbartools.setObjectName('Tools_TB')
  3354. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  3355. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  3356. # self.ui.geo_edit_toolbar.setVisible(False)
  3357. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  3358. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  3359. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  3360. # self.ui.grb_edit_toolbar.setVisible(False)
  3361. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  3362. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  3363. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  3364. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  3365. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  3366. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  3367. self.ui.snap_toolbar.setObjectName('Snap_TB')
  3368. self.ui.snap_toolbar.setMaximumHeight(30)
  3369. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  3370. self.ui.corner_snap_btn.setVisible(True)
  3371. self.ui.snap_magnet.setVisible(True)
  3372. # add all the actions to the toolbars
  3373. self.ui.populate_toolbars()
  3374. # reconnect all the signals to the toolbar actions
  3375. self.connect_toolbar_signals()
  3376. self.ui.grid_snap_btn.setChecked(True)
  3377. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  3378. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  3379. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  3380. self.ui.grid_gap_link_cb.setChecked(True)
  3381. def on_cnc_custom_parameters(self, signal_text):
  3382. if signal_text == 'Parameters':
  3383. return
  3384. else:
  3385. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  3386. def on_save_button(self):
  3387. self.save_defaults(silent=False)
  3388. # load the defaults so they are updated into the app
  3389. self.load_defaults(filename='current_defaults')
  3390. # Re-fresh project options
  3391. self.on_options_app2project()
  3392. def handlePrint(self):
  3393. self.report_usage("handlePrint()")
  3394. dialog = QtPrintSupport.QPrintDialog()
  3395. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3396. self.ui.code_editor.document().print_(dialog.printer())
  3397. def handlePreview(self):
  3398. self.report_usage("handlePreview()")
  3399. dialog = QtPrintSupport.QPrintPreviewDialog()
  3400. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3401. dialog.exec_()
  3402. def handleTextChanged(self):
  3403. # enable = not self.ui.code_editor.document().isEmpty()
  3404. # self.ui.buttonPrint.setEnabled(enable)
  3405. # self.ui.buttonPreview.setEnabled(enable)
  3406. pass
  3407. def handleOpen(self, filt=None):
  3408. self.report_usage("handleOpen()")
  3409. if filt:
  3410. _filter_ = filt
  3411. else:
  3412. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3413. "All Files (*.*)"
  3414. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  3415. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  3416. if path:
  3417. file = QtCore.QFile(path)
  3418. if file.open(QtCore.QIODevice.ReadOnly):
  3419. stream = QtCore.QTextStream(file)
  3420. self.gcode_edited = stream.readAll()
  3421. self.ui.code_editor.setPlainText(self.gcode_edited)
  3422. file.close()
  3423. def handleSaveGCode(self,name=None, filt=None):
  3424. self.report_usage("handleSaveGCode()")
  3425. if filt:
  3426. _filter_ = filt
  3427. else:
  3428. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3429. "All Files (*.*)"
  3430. if name:
  3431. obj_name = name
  3432. else:
  3433. try:
  3434. obj_name = self.collection.get_active().options['name']
  3435. except AttributeError:
  3436. obj_name = 'file'
  3437. if filt is None:
  3438. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3439. try:
  3440. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3441. caption=_("Export G-Code ..."),
  3442. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3443. filter=_filter_
  3444. )[0])
  3445. except TypeError:
  3446. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  3447. if filename == "":
  3448. self.inform.emit(_("[WARNING_NOTCL] Export Code cancelled."))
  3449. return
  3450. else:
  3451. try:
  3452. my_gcode = self.ui.code_editor.toPlainText()
  3453. with open(filename, 'w') as f:
  3454. for line in my_gcode:
  3455. f.write(line)
  3456. except FileNotFoundError:
  3457. self.inform.emit(_("[WARNING] No such file or directory"))
  3458. return
  3459. # Just for adding it to the recent files list.
  3460. self.file_opened.emit("cncjob", filename)
  3461. self.file_saved.emit("cncjob", filename)
  3462. self.inform.emit(_("Saved to: %s") % filename)
  3463. def handleFindGCode(self):
  3464. self.report_usage("handleFindGCode()")
  3465. flags = QtGui.QTextDocument.FindCaseSensitively
  3466. text_to_be_found = self.ui.entryFind.get_value()
  3467. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3468. if r is False:
  3469. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3470. def handleReplaceGCode(self):
  3471. self.report_usage("handleReplaceGCode()")
  3472. old = self.ui.entryFind.get_value()
  3473. new = self.ui.entryReplace.get_value()
  3474. if self.ui.sel_all_cb.isChecked():
  3475. while True:
  3476. cursor = self.ui.code_editor.textCursor()
  3477. cursor.beginEditBlock()
  3478. flags = QtGui.QTextDocument.FindCaseSensitively
  3479. # self.ui.editor is the QPlainTextEdit
  3480. r = self.ui.code_editor.find(str(old), flags)
  3481. if r:
  3482. qc = self.ui.code_editor.textCursor()
  3483. if qc.hasSelection():
  3484. qc.insertText(new)
  3485. else:
  3486. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3487. break
  3488. # Mark end of undo block
  3489. cursor.endEditBlock()
  3490. else:
  3491. cursor = self.ui.code_editor.textCursor()
  3492. cursor.beginEditBlock()
  3493. qc = self.ui.code_editor.textCursor()
  3494. if qc.hasSelection():
  3495. qc.insertText(new)
  3496. # Mark end of undo block
  3497. cursor.endEditBlock()
  3498. def on_tool_add_keypress(self):
  3499. ## Current application units in Upper Case
  3500. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3501. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3502. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3503. if notebook_widget_name == 'selected_tab':
  3504. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3505. # Tool add works for Geometry only if Advanced is True in Preferences
  3506. if self.defaults["global_app_level"] == 'a':
  3507. tool_add_popup = FCInputDialog(title="New Tool ...",
  3508. text='Enter a Tool Diameter:',
  3509. min=0.0000, max=99.9999, decimals=4)
  3510. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3511. val, ok = tool_add_popup.get_value()
  3512. if ok:
  3513. if float(val) == 0:
  3514. self.inform.emit(
  3515. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3516. return
  3517. self.collection.get_active().on_tool_add(dia=float(val))
  3518. else:
  3519. self.inform.emit(
  3520. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3521. else:
  3522. msgbox = QtWidgets.QMessageBox()
  3523. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3524. "Go to Preferences -> General - Show Advanced Options."))
  3525. msgbox.setWindowTitle("Tool adding ...")
  3526. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3527. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3528. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3529. msgbox.exec_()
  3530. # work only if the notebook tab on focus is the Tools_Tab
  3531. if notebook_widget_name == 'tool_tab':
  3532. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3533. tool_add_popup = FCInputDialog(title="New Tool ...",
  3534. text='Enter a Tool Diameter:',
  3535. min=0.0000, max=99.9999, decimals=4)
  3536. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3537. val, ok = tool_add_popup.get_value()
  3538. # and only if the tool is NCC Tool
  3539. if tool_widget == self.ncclear_tool.toolName:
  3540. if ok:
  3541. if float(val) == 0:
  3542. self.inform.emit(
  3543. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3544. return
  3545. self.ncclear_tool.on_tool_add(dia=float(val))
  3546. else:
  3547. self.inform.emit(
  3548. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3549. # and only if the tool is Paint Area Tool
  3550. elif tool_widget == self.paint_tool.toolName:
  3551. if ok:
  3552. if float(val) == 0:
  3553. self.inform.emit(
  3554. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3555. return
  3556. self.paint_tool.on_tool_add(dia=float(val))
  3557. else:
  3558. self.inform.emit(
  3559. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3560. # and only if the tool is Solder Paste Dispensing Tool
  3561. elif tool_widget == self.paste_tool.toolName:
  3562. if ok:
  3563. if float(val) == 0:
  3564. self.inform.emit(
  3565. _("[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format."))
  3566. return
  3567. self.paste_tool.on_tool_add(dia=float(val))
  3568. else:
  3569. self.inform.emit(
  3570. _("[WARNING_NOTCL] Adding Tool cancelled ..."))
  3571. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3572. # See description bellow.
  3573. def on_delete_keypress(self):
  3574. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3575. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3576. if notebook_widget_name == 'selected_tab':
  3577. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3578. self.collection.get_active().on_tool_delete()
  3579. # work only if the notebook tab on focus is the Tools_Tab
  3580. elif notebook_widget_name == 'tool_tab':
  3581. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3582. # and only if the tool is NCC Tool
  3583. if tool_widget == self.ncclear_tool.toolName:
  3584. self.ncclear_tool.on_tool_delete()
  3585. # and only if the tool is Paint Tool
  3586. elif tool_widget == self.paint_tool.toolName:
  3587. self.paint_tool.on_tool_delete()
  3588. # and only if the tool is Solder Paste Dispensing Tool
  3589. elif tool_widget == self.paste_tool.toolName:
  3590. self.paste_tool.on_tool_delete()
  3591. else:
  3592. self.on_delete()
  3593. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3594. # some screens you have to be careful where you hover with your mouse.
  3595. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3596. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3597. # Complicated, I know :)
  3598. def on_delete(self):
  3599. """
  3600. Delete the currently selected FlatCAMObjs.
  3601. :return: None
  3602. """
  3603. self.report_usage("on_delete()")
  3604. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3605. # a geometry object before we update it.
  3606. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3607. if self.collection.get_active():
  3608. self.log.debug("on_delete()")
  3609. self.report_usage("on_delete")
  3610. while (self.collection.get_active()):
  3611. self.delete_first_selected()
  3612. self.inform.emit(_("Object(s) deleted ..."))
  3613. # make sure that the selection shape is deleted, too
  3614. self.delete_selection_shape()
  3615. else:
  3616. self.inform.emit(_("Failed. No object(s) selected..."))
  3617. else:
  3618. self.inform.emit(_("Save the work in Editor and try again ..."))
  3619. def on_set_origin(self):
  3620. """
  3621. Set the origin to the left mouse click position
  3622. :return: None
  3623. """
  3624. #display the message for the user
  3625. #and ask him to click on the desired position
  3626. self.report_usage("on_set_origin()")
  3627. self.inform.emit(_('Click to set the origin ...'))
  3628. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3629. def on_jump_to(self, custom_location=None):
  3630. """
  3631. Jump to a location by setting the mouse cursor location
  3632. :return:
  3633. """
  3634. self.report_usage("on_jump_to()")
  3635. if custom_location is None:
  3636. dia_box = Dialog_box(title=_("Jump to ..."),
  3637. label=_("Enter the coordinates in format X,Y:"),
  3638. icon=QtGui.QIcon('share/jump_to16.png'))
  3639. if dia_box.ok is True:
  3640. try:
  3641. location = eval(dia_box.location)
  3642. if not isinstance(location, tuple):
  3643. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3644. return
  3645. except:
  3646. return
  3647. else:
  3648. return
  3649. else:
  3650. location = custom_location
  3651. self.plotcanvas.fit_center(loc=location)
  3652. cursor = QtGui.QCursor()
  3653. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3654. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3655. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3656. self.inform.emit(_("Done."))
  3657. def on_copy_object(self):
  3658. self.report_usage("on_copy_object()")
  3659. def initialize(obj_init, app):
  3660. obj_init.solid_geometry = obj.solid_geometry
  3661. try:
  3662. obj_init.follow_geometry = obj.follow_geometry
  3663. except:
  3664. pass
  3665. try:
  3666. obj_init.apertures = obj.apertures
  3667. except:
  3668. pass
  3669. try:
  3670. if obj.tools:
  3671. obj_init.tools = obj.tools
  3672. except Exception as e:
  3673. log.debug("on_copy_object() --> %s" % str(e))
  3674. def initialize_excellon(obj_init, app):
  3675. obj_init.tools = obj.tools
  3676. # drills are offset, so they need to be deep copied
  3677. obj_init.drills = deepcopy(obj.drills)
  3678. # slots are offset, so they need to be deep copied
  3679. obj_init.slots = deepcopy(obj.slots)
  3680. obj_init.create_geometry()
  3681. for obj in self.collection.get_selected():
  3682. obj_name = obj.options["name"]
  3683. try:
  3684. if isinstance(obj, FlatCAMExcellon):
  3685. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3686. elif isinstance(obj,FlatCAMGerber):
  3687. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3688. elif isinstance(obj,FlatCAMGeometry):
  3689. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3690. except Exception as e:
  3691. return "Operation failed: %s" % str(e)
  3692. def on_copy_object2(self, custom_name):
  3693. def initialize_geometry(obj_init, app):
  3694. obj_init.solid_geometry = obj.solid_geometry
  3695. try:
  3696. obj_init.follow_geometry = obj.follow_geometry
  3697. except:
  3698. pass
  3699. try:
  3700. obj_init.apertures = obj.apertures
  3701. except:
  3702. pass
  3703. try:
  3704. if obj.tools:
  3705. obj_init.tools = obj.tools
  3706. except Exception as e:
  3707. log.debug("on_copy_object2() --> %s" % str(e))
  3708. def initialize_gerber(obj_init, app):
  3709. obj_init.solid_geometry = obj.solid_geometry
  3710. obj_init.apertures = deepcopy(obj.apertures)
  3711. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3712. def initialize_excellon(obj_init, app):
  3713. obj_init.tools = obj.tools
  3714. # drills are offset, so they need to be deep copied
  3715. obj_init.drills = deepcopy(obj.drills)
  3716. # slots are offset, so they need to be deep copied
  3717. obj_init.slots = deepcopy(obj.slots)
  3718. obj_init.create_geometry()
  3719. for obj in self.collection.get_selected():
  3720. obj_name = obj.options["name"]
  3721. try:
  3722. if isinstance(obj, FlatCAMExcellon):
  3723. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3724. elif isinstance(obj,FlatCAMGerber):
  3725. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3726. elif isinstance(obj,FlatCAMGeometry):
  3727. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3728. except Exception as e:
  3729. return "Operation failed: %s" % str(e)
  3730. def on_rename_object(self, text):
  3731. self.report_usage("on_rename_object()")
  3732. named_obj = self.collection.get_active()
  3733. for obj in named_obj:
  3734. if obj is list:
  3735. self.on_rename_object(text)
  3736. else:
  3737. try:
  3738. obj.options['name'] = text
  3739. except:
  3740. log.warning("Could not rename the object in the list")
  3741. def on_copy_object_as_geometry(self):
  3742. self.report_usage("on_copy_object_as_geometry()")
  3743. def initialize(obj_init, app):
  3744. obj_init.solid_geometry = obj.solid_geometry
  3745. try:
  3746. obj_init.follow_geometry = obj.follow_geometry
  3747. except:
  3748. pass
  3749. try:
  3750. obj_init.apertures = obj.apertures
  3751. except:
  3752. pass
  3753. if obj.tools:
  3754. obj_init.tools = obj.tools
  3755. def initialize_excellon(obj, app):
  3756. objs = self.collection.get_selected()
  3757. FlatCAMGeometry.merge(objs, obj)
  3758. for obj in self.collection.get_selected():
  3759. obj_name = obj.options["name"]
  3760. try:
  3761. if isinstance(obj, FlatCAMExcellon):
  3762. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3763. else:
  3764. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3765. except Exception as e:
  3766. return "Operation failed: %s" % str(e)
  3767. def on_set_zero_click(self, event):
  3768. #this function will be available only for mouse left click
  3769. pos =[]
  3770. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3771. if event.button == 1:
  3772. if self.grid_status() == True:
  3773. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3774. else:
  3775. pos = pos_canvas
  3776. x = 0 - pos[0]
  3777. y = 0 - pos[1]
  3778. for obj in self.collection.get_list():
  3779. obj.offset((x,y))
  3780. self.object_changed.emit(obj)
  3781. obj.plot()
  3782. # Update the object bounding box options
  3783. a, b, c, d = obj.bounds()
  3784. obj.options['xmin'] = a
  3785. obj.options['ymin'] = b
  3786. obj.options['xmax'] = c
  3787. obj.options['ymax'] = d
  3788. # self.plot_all(zoom=False)
  3789. self.inform.emit(_('[success] Origin set ...'))
  3790. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3791. self.should_we_save = True
  3792. def on_selectall(self):
  3793. self.report_usage("on_selectall()")
  3794. # delete the possible selection box around a possible selected object
  3795. self.delete_selection_shape()
  3796. for name in self.collection.get_names():
  3797. self.collection.set_active(name)
  3798. curr_sel_obj = self.collection.get_by_name(name)
  3799. # create the selection box around the selected object
  3800. self.draw_selection_shape(curr_sel_obj)
  3801. def on_preferences(self):
  3802. # add the tab if it was closed
  3803. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  3804. # delete the absolute and relative position and messages in the infobar
  3805. self.ui.position_label.setText("")
  3806. self.ui.rel_position_label.setText("")
  3807. # Switch plot_area to preferences page
  3808. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3809. self.ui.show()
  3810. def on_flipy(self):
  3811. self.report_usage("on_flipy()")
  3812. obj_list = self.collection.get_selected()
  3813. xminlist = []
  3814. yminlist = []
  3815. xmaxlist = []
  3816. ymaxlist = []
  3817. if not obj_list:
  3818. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on Y axis."))
  3819. else:
  3820. try:
  3821. # first get a bounding box to fit all
  3822. for obj in obj_list:
  3823. xmin, ymin, xmax, ymax = obj.bounds()
  3824. xminlist.append(xmin)
  3825. yminlist.append(ymin)
  3826. xmaxlist.append(xmax)
  3827. ymaxlist.append(ymax)
  3828. # get the minimum x,y and maximum x,y for all objects selected
  3829. xminimal = min(xminlist)
  3830. yminimal = min(yminlist)
  3831. xmaximal = max(xmaxlist)
  3832. ymaximal = max(ymaxlist)
  3833. px = 0.5 * (xminimal + xmaximal)
  3834. py = 0.5 * (yminimal + ymaximal)
  3835. # execute mirroring
  3836. for obj in obj_list:
  3837. obj.mirror('X', [px, py])
  3838. obj.plot()
  3839. self.object_changed.emit(obj)
  3840. self.inform.emit(_("[success] Flip on Y axis done."))
  3841. except Exception as e:
  3842. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3843. return
  3844. def on_flipx(self):
  3845. self.report_usage("on_flipx()")
  3846. obj_list = self.collection.get_selected()
  3847. xminlist = []
  3848. yminlist = []
  3849. xmaxlist = []
  3850. ymaxlist = []
  3851. if not obj_list:
  3852. self.inform.emit(_("[WARNING_NOTCL] No object selected to Flip on X axis."))
  3853. else:
  3854. try:
  3855. # first get a bounding box to fit all
  3856. for obj in obj_list:
  3857. xmin, ymin, xmax, ymax = obj.bounds()
  3858. xminlist.append(xmin)
  3859. yminlist.append(ymin)
  3860. xmaxlist.append(xmax)
  3861. ymaxlist.append(ymax)
  3862. # get the minimum x,y and maximum x,y for all objects selected
  3863. xminimal = min(xminlist)
  3864. yminimal = min(yminlist)
  3865. xmaximal = max(xmaxlist)
  3866. ymaximal = max(ymaxlist)
  3867. px = 0.5 * (xminimal + xmaximal)
  3868. py = 0.5 * (yminimal + ymaximal)
  3869. # execute mirroring
  3870. for obj in obj_list:
  3871. obj.mirror('Y', [px, py])
  3872. obj.plot()
  3873. self.object_changed.emit(obj)
  3874. self.inform.emit(_("[success] Flip on X axis done."))
  3875. except Exception as e:
  3876. self.inform.emit(_("[ERROR_NOTCL] Due of %s, Flip action was not executed.") % str(e))
  3877. return
  3878. def on_rotate(self, silent=False, preset=None):
  3879. self.report_usage("on_rotate()")
  3880. obj_list = self.collection.get_selected()
  3881. xminlist = []
  3882. yminlist = []
  3883. xmaxlist = []
  3884. ymaxlist = []
  3885. if not obj_list:
  3886. self.inform.emit(_("[WARNING_NOTCL] No object selected to Rotate."))
  3887. else:
  3888. if silent is False:
  3889. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3890. min=-360, max=360, decimals=4,
  3891. init_val=float(self.defaults['tools_transform_rotate']))
  3892. num, ok = rotatebox.get_value()
  3893. else:
  3894. num = preset
  3895. ok = True
  3896. if ok:
  3897. try:
  3898. # first get a bounding box to fit all
  3899. for obj in obj_list:
  3900. xmin, ymin, xmax, ymax = obj.bounds()
  3901. xminlist.append(xmin)
  3902. yminlist.append(ymin)
  3903. xmaxlist.append(xmax)
  3904. ymaxlist.append(ymax)
  3905. # get the minimum x,y and maximum x,y for all objects selected
  3906. xminimal = min(xminlist)
  3907. yminimal = min(yminlist)
  3908. xmaximal = max(xmaxlist)
  3909. ymaximal = max(ymaxlist)
  3910. px = 0.5 * (xminimal + xmaximal)
  3911. py = 0.5 * (yminimal + ymaximal)
  3912. for sel_obj in obj_list:
  3913. sel_obj.rotate(-float(num), point=(px, py))
  3914. sel_obj.plot()
  3915. self.object_changed.emit(sel_obj)
  3916. self.inform.emit(_("[success] Rotation done."))
  3917. except Exception as e:
  3918. self.inform.emit(_("[ERROR_NOTCL] Due of %s, rotation movement was not executed.") % str(e))
  3919. return
  3920. def on_skewx(self):
  3921. self.report_usage("on_skewx()")
  3922. obj_list = self.collection.get_selected()
  3923. xminlist = []
  3924. yminlist = []
  3925. if not obj_list:
  3926. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on X axis."))
  3927. else:
  3928. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3929. min=-360, max=360, decimals=4,
  3930. init_val=float(self.defaults['tools_transform_skew_x']))
  3931. num, ok = skewxbox.get_value()
  3932. if ok:
  3933. # first get a bounding box to fit all
  3934. for obj in obj_list:
  3935. xmin, ymin, xmax, ymax = obj.bounds()
  3936. xminlist.append(xmin)
  3937. yminlist.append(ymin)
  3938. # get the minimum x,y and maximum x,y for all objects selected
  3939. xminimal = min(xminlist)
  3940. yminimal = min(yminlist)
  3941. for obj in obj_list:
  3942. obj.skew(num, 0, point=(xminimal, yminimal))
  3943. obj.plot()
  3944. self.object_changed.emit(obj)
  3945. self.inform.emit(_("[success] Skew on X axis done."))
  3946. def on_skewy(self):
  3947. self.report_usage("on_skewy()")
  3948. obj_list = self.collection.get_selected()
  3949. xminlist = []
  3950. yminlist = []
  3951. if not obj_list:
  3952. self.inform.emit(_("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis."))
  3953. else:
  3954. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  3955. min=-360, max=360, decimals=4,
  3956. init_val=float(self.defaults['tools_transform_skew_y']))
  3957. num, ok = skewybox.get_value()
  3958. if ok:
  3959. # first get a bounding box to fit all
  3960. for obj in obj_list:
  3961. xmin, ymin, xmax, ymax = obj.bounds()
  3962. xminlist.append(xmin)
  3963. yminlist.append(ymin)
  3964. # get the minimum x,y and maximum x,y for all objects selected
  3965. xminimal = min(xminlist)
  3966. yminimal = min(yminlist)
  3967. for obj in obj_list:
  3968. obj.skew(0, num, point=(xminimal, yminimal))
  3969. obj.plot()
  3970. self.object_changed.emit(obj)
  3971. self.inform.emit(_("[success] Skew on Y axis done."))
  3972. def delete_first_selected(self):
  3973. # Keep this for later
  3974. try:
  3975. name = self.collection.get_active().options["name"]
  3976. except AttributeError:
  3977. self.log.debug("Nothing selected for deletion")
  3978. return
  3979. # Remove plot
  3980. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3981. # self.plotcanvas.auto_adjust_axes()
  3982. # Clear form
  3983. self.setup_component_editor()
  3984. # Remove from dictionary
  3985. self.collection.delete_active()
  3986. self.inform.emit("Object deleted: %s" % name)
  3987. def on_plots_updated(self):
  3988. """
  3989. Callback used to report when the plots have changed.
  3990. Adjust axes and zooms to fit.
  3991. :return: None
  3992. """
  3993. # self.plotcanvas.auto_adjust_axes()
  3994. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3995. self.on_zoom_fit(None)
  3996. # TODO: Rework toolbar 'clear', 'replot' functions
  3997. def on_toolbar_replot(self):
  3998. """
  3999. Callback for toolbar button. Re-plots all objects.
  4000. :return: None
  4001. """
  4002. self.report_usage("on_toolbar_replot")
  4003. self.log.debug("on_toolbar_replot()")
  4004. try:
  4005. self.collection.get_active().read_form()
  4006. except AttributeError:
  4007. self.log.debug("on_toolbar_replot(): AttributeError")
  4008. pass
  4009. self.plot_all()
  4010. def on_row_activated(self, index):
  4011. if index.isValid():
  4012. if index.internalPointer().parent_item != self.collection.root_item:
  4013. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4014. def grid_status(self):
  4015. if self.ui.grid_snap_btn.isChecked():
  4016. return 1
  4017. else:
  4018. return 0
  4019. def populate_cmenu_grids(self):
  4020. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4021. self.ui.cmenu_gridmenu.clear()
  4022. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4023. for grid in sorted_list:
  4024. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  4025. action.triggered.connect(self.set_grid)
  4026. self.ui.cmenu_gridmenu.addSeparator()
  4027. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  4028. grid_add.triggered.connect(self.on_grid_add)
  4029. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  4030. grid_delete.triggered.connect(self.on_grid_delete)
  4031. def set_grid(self):
  4032. self.ui.grid_gap_x_entry.setText(self.sender().text())
  4033. self.ui.grid_gap_y_entry.setText(self.sender().text())
  4034. def on_grid_add(self):
  4035. ## Current application units in lower Case
  4036. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4037. grid_add_popup = FCInputDialog(title="New Grid ...",
  4038. text='Enter a Grid VAlue:',
  4039. min=0.0000, max=99.9999, decimals=4)
  4040. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  4041. val, ok = grid_add_popup.get_value()
  4042. if ok:
  4043. if float(val) == 0:
  4044. self.inform.emit(
  4045. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4046. return
  4047. else:
  4048. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4049. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4050. self.inform.emit(
  4051. _("[success] New Grid added ..."))
  4052. else:
  4053. self.inform.emit(
  4054. _("[WARNING_NOTCL] Grid already exists ..."))
  4055. else:
  4056. self.inform.emit(
  4057. _("[WARNING_NOTCL] Adding New Grid cancelled ..."))
  4058. def on_grid_delete(self):
  4059. ## Current application units in lower Case
  4060. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  4061. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4062. text='Enter a Grid Value:',
  4063. min=0.0000, max=99.9999, decimals=4)
  4064. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  4065. val, ok = grid_del_popup.get_value()
  4066. if ok:
  4067. if float(val) == 0:
  4068. self.inform.emit(
  4069. _("[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format."))
  4070. return
  4071. else:
  4072. try:
  4073. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4074. except ValueError:
  4075. self.inform.emit(
  4076. _("[ERROR_NOTCL] Grid Value does not exist ..."))
  4077. return
  4078. self.inform.emit(
  4079. _("[success] Grid Value deleted ..."))
  4080. else:
  4081. self.inform.emit(
  4082. _("[WARNING_NOTCL] Delete Grid value cancelled ..."))
  4083. def on_shortcut_list(self):
  4084. self.report_usage("on_shortcut_list()")
  4085. # add the tab if it was closed
  4086. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  4087. # delete the absolute and relative position and messages in the infobar
  4088. self.ui.position_label.setText("")
  4089. self.ui.rel_position_label.setText("")
  4090. # Switch plot_area to preferences page
  4091. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4092. self.ui.show()
  4093. def on_select_tab(self, name):
  4094. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4095. if self.ui.splitter.sizes()[0] == 0:
  4096. self.ui.splitter.setSizes([1, 1])
  4097. else:
  4098. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4099. self.ui.splitter.setSizes([0, 1])
  4100. if name == 'project':
  4101. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4102. elif name == 'selected':
  4103. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4104. elif name == 'tool':
  4105. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4106. def on_copy_name(self):
  4107. self.report_usage("on_copy_name()")
  4108. obj = self.collection.get_active()
  4109. try:
  4110. name = obj.options["name"]
  4111. except AttributeError:
  4112. log.debug("on_copy_name() --> No object selected to copy it's name")
  4113. self.inform.emit(_("[WARNING_NOTCL] No object selected to copy it's name"))
  4114. return
  4115. self.clipboard.setText(name)
  4116. self.inform.emit(_("Name copied on clipboard ..."))
  4117. def on_mouse_click_over_plot(self, event):
  4118. """
  4119. Default actions are:
  4120. :param event: Contains information about the event, like which button
  4121. was clicked, the pixel coordinates and the axes coordinates.
  4122. :return: None
  4123. """
  4124. self.pos = []
  4125. # So it can receive key presses
  4126. self.plotcanvas.vispy_canvas.native.setFocus()
  4127. # Set the mouse button for panning
  4128. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  4129. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4130. if self.grid_status() == True:
  4131. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4132. self.app_cursor.enabled = True
  4133. else:
  4134. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4135. self.app_cursor.enabled = False
  4136. try:
  4137. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4138. if event.button == 1:
  4139. # Reset here the relative coordinates so there is a new reference on the click position
  4140. if self.rel_point1 is None:
  4141. self.rel_point1 = self.pos
  4142. else:
  4143. self.rel_point2 = copy(self.rel_point1)
  4144. self.rel_point1 = self.pos
  4145. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  4146. if modifiers == QtCore.Qt.ShiftModifier:
  4147. # do not auto open the Project Tab
  4148. self.click_noproject = True
  4149. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  4150. return
  4151. self.on_mouse_move_over_plot(event, origin_click=True)
  4152. except Exception as e:
  4153. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4154. def on_double_click_over_plot(self, event):
  4155. self.doubleclick = True
  4156. def on_mouse_move_over_plot(self, event, origin_click=None):
  4157. """
  4158. Callback for the mouse motion event over the plot. This event is generated
  4159. by the Matplotlib backend and has been registered in ``self.__init__()``.
  4160. For details, see: http://matplotlib.org/users/event_handling.html
  4161. :param event: Contains information about the event.
  4162. :param origin_click
  4163. :return: None
  4164. """
  4165. # So it can receive key presses
  4166. self.plotcanvas.vispy_canvas.native.setFocus()
  4167. self.pos_jump = event.pos
  4168. if origin_click is True:
  4169. pass
  4170. else:
  4171. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4172. if event.button == 2:
  4173. self.panning_action = True
  4174. return
  4175. else:
  4176. self.panning_action = False
  4177. if self.rel_point1 is not None:
  4178. try: # May fail in case mouse not within axes
  4179. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4180. if self.grid_status():
  4181. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4182. self.app_cursor.enabled = True
  4183. # Update cursor
  4184. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  4185. else:
  4186. pos = (pos_canvas[0], pos_canvas[1])
  4187. self.app_cursor.enabled = False
  4188. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4189. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  4190. dx = pos[0] - self.rel_point1[0]
  4191. dy = pos[1] - self.rel_point1[1]
  4192. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4193. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4194. self.mouse = [pos[0], pos[1]]
  4195. # if the mouse is moved and the LMB is clicked then the action is a selection
  4196. if event.is_dragging == 1 and event.button == 1:
  4197. self.delete_selection_shape()
  4198. if dx < 0:
  4199. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4200. face_color=self.defaults['global_alt_sel_fill'])
  4201. self.selection_type = False
  4202. else:
  4203. self.draw_moving_selection_shape(self.pos, pos)
  4204. self.selection_type = True
  4205. # hover effect - enabled in Preferences -> General -> GUI Settings
  4206. if self.defaults['global_hover']:
  4207. for obj in self.collection.get_list():
  4208. try:
  4209. # select the object(s) only if it is enabled (plotted)
  4210. if obj.options['plot']:
  4211. if obj not in self.collection.get_selected():
  4212. poly_obj = Polygon(
  4213. [(obj.options['xmin'], obj.options['ymin']),
  4214. (obj.options['xmax'], obj.options['ymin']),
  4215. (obj.options['xmax'], obj.options['ymax']),
  4216. (obj.options['xmin'], obj.options['ymax'])]
  4217. )
  4218. if Point(pos).within(poly_obj):
  4219. if obj.isHovering is False:
  4220. obj.isHovering = True
  4221. obj.notHovering = True
  4222. # create the selection box around the selected object
  4223. self.draw_hover_shape(obj, color='#d1e0e0')
  4224. else:
  4225. if obj.notHovering is True:
  4226. obj.notHovering = False
  4227. obj.isHovering = False
  4228. self.delete_hover_shape()
  4229. except:
  4230. # the Exception here will happen if we try to select on screen and we have an
  4231. # newly (and empty) just created Geometry or Excellon object that do not have the
  4232. # xmin, xmax, ymin, ymax options.
  4233. # In this case poly_obj creation (see above) will fail
  4234. pass
  4235. except:
  4236. self.ui.position_label.setText("")
  4237. self.ui.rel_position_label.setText("")
  4238. self.mouse = None
  4239. def on_mouse_click_release_over_plot(self, event):
  4240. """
  4241. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4242. and has been registered in ''self.__init__()''.
  4243. :param event: contains information about the event.
  4244. :return:
  4245. """
  4246. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  4247. if self.grid_status():
  4248. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4249. else:
  4250. pos = (pos_canvas[0], pos_canvas[1])
  4251. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  4252. # canvas menu
  4253. try:
  4254. if event.button == 2: # right click
  4255. if self.panning_action is True:
  4256. self.panning_action = False
  4257. else:
  4258. self.cursor = QtGui.QCursor()
  4259. self.populate_cmenu_grids()
  4260. self.ui.popMenu.popup(self.cursor.pos())
  4261. except Exception as e:
  4262. log.warning("Error: %s" % str(e))
  4263. return
  4264. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  4265. # selection and then select a type of selection ("enclosing" or "touching")
  4266. try:
  4267. if event.button == 1: # left click
  4268. if self.doubleclick is True:
  4269. self.doubleclick = False
  4270. if self.collection.get_selected():
  4271. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4272. if self.ui.splitter.sizes()[0] == 0:
  4273. self.ui.splitter.setSizes([1, 1])
  4274. # delete the selection shape(S) as it may be in the way
  4275. self.delete_selection_shape()
  4276. self.delete_hover_shape()
  4277. else:
  4278. if self.selection_type is not None:
  4279. self.selection_area_handler(self.pos, pos, self.selection_type)
  4280. self.selection_type = None
  4281. else:
  4282. modifiers = QtWidgets.QApplication.keyboardModifiers()
  4283. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  4284. # and if it's not selected then it will be selected
  4285. if modifiers == QtCore.Qt.ControlModifier:
  4286. # If there is no active command (self.command_active is None) then we check if we clicked on
  4287. # a object by checking the bounding limits against mouse click position
  4288. if self.command_active is None:
  4289. self.select_objects(key='CTRL')
  4290. self.delete_hover_shape()
  4291. else:
  4292. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  4293. # checking the bounding limits against mouse click position
  4294. if self.command_active is None:
  4295. self.select_objects()
  4296. self.delete_hover_shape()
  4297. except Exception as e:
  4298. log.warning("Error: %s" % str(e))
  4299. return
  4300. def selection_area_handler(self, start_pos, end_pos, sel_type):
  4301. """
  4302. :param start_pos: mouse position when the selection LMB click was done
  4303. :param end_pos: mouse position when the left mouse button is released
  4304. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  4305. :return:
  4306. """
  4307. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  4308. self.delete_selection_shape()
  4309. for obj in self.collection.get_list():
  4310. try:
  4311. # select the object(s) only if it is enabled (plotted)
  4312. if obj.options['plot']:
  4313. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  4314. (obj.options['xmax'], obj.options['ymin']),
  4315. (obj.options['xmax'], obj.options['ymax']),
  4316. (obj.options['xmin'], obj.options['ymax'])])
  4317. if sel_type is True:
  4318. if poly_obj.within(poly_selection):
  4319. # create the selection box around the selected object
  4320. self.draw_selection_shape(obj)
  4321. self.collection.set_active(obj.options['name'])
  4322. else:
  4323. if poly_selection.intersects(poly_obj):
  4324. # create the selection box around the selected object
  4325. self.draw_selection_shape(obj)
  4326. self.collection.set_active(obj.options['name'])
  4327. except:
  4328. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  4329. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  4330. # In this case poly_obj creation (see above) will fail
  4331. pass
  4332. def select_objects(self, key=None):
  4333. # list where we store the overlapped objects under our mouse left click position
  4334. objects_under_the_click_list = []
  4335. # Populate the list with the overlapped objects on the click position
  4336. curr_x, curr_y = self.pos
  4337. for obj in self.all_objects_list:
  4338. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  4339. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  4340. if obj.options['name'] not in objects_under_the_click_list:
  4341. if obj.options['plot']:
  4342. # add objects to the objects_under_the_click list only if the object is plotted
  4343. # (active and not disabled)
  4344. objects_under_the_click_list.append(obj.options['name'])
  4345. try:
  4346. # If there is no element in the overlapped objects list then make everyone inactive
  4347. # because we selected "nothing"
  4348. if not objects_under_the_click_list:
  4349. self.collection.set_all_inactive()
  4350. # delete the possible selection box around a possible selected object
  4351. self.delete_selection_shape()
  4352. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  4353. # only when working on App
  4354. if self.call_source == 'app':
  4355. if self.click_noproject is False:
  4356. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4357. else:
  4358. # restore auto open the Project Tab
  4359. self.click_noproject = False
  4360. # delete any text in the status bar, implicitly the last object name that was selected
  4361. self.inform.emit("")
  4362. else:
  4363. self.call_source = 'app'
  4364. else:
  4365. # case when there is only an object under the click and we toggle it
  4366. if len(objects_under_the_click_list) == 1:
  4367. if self.collection.get_active() is None :
  4368. self.collection.set_active(objects_under_the_click_list[0])
  4369. # create the selection box around the selected object
  4370. curr_sel_obj = self.collection.get_active()
  4371. self.draw_selection_shape(curr_sel_obj)
  4372. # self.inform.emit('[selected] %s: %s selected' %
  4373. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4374. if curr_sel_obj.kind == 'gerber':
  4375. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4376. color='green', name=str(curr_sel_obj.options['name'])))
  4377. elif curr_sel_obj.kind == 'excellon':
  4378. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4379. color='brown', name=str(curr_sel_obj.options['name'])))
  4380. elif curr_sel_obj.kind == 'cncjob':
  4381. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4382. color='blue', name=str(curr_sel_obj.options['name'])))
  4383. elif curr_sel_obj.kind == 'geometry':
  4384. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4385. color='red', name=str(curr_sel_obj.options['name'])))
  4386. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  4387. self.collection.set_all_inactive()
  4388. self.delete_selection_shape()
  4389. self.collection.set_active(objects_under_the_click_list[0])
  4390. # create the selection box around the selected object
  4391. curr_sel_obj = self.collection.get_active()
  4392. self.draw_selection_shape(curr_sel_obj)
  4393. # self.inform.emit('[selected] %s: %s selected' %
  4394. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4395. if curr_sel_obj.kind == 'gerber':
  4396. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4397. color='green', name=str(curr_sel_obj.options['name'])))
  4398. elif curr_sel_obj.kind == 'excellon':
  4399. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4400. color='brown', name=str(curr_sel_obj.options['name'])))
  4401. elif curr_sel_obj.kind == 'cncjob':
  4402. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4403. color='blue', name=str(curr_sel_obj.options['name'])))
  4404. elif curr_sel_obj.kind == 'geometry':
  4405. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4406. color='red', name=str(curr_sel_obj.options['name'])))
  4407. else:
  4408. self.collection.set_all_inactive()
  4409. self.delete_selection_shape()
  4410. if self.call_source == 'app':
  4411. # delete any text in the status bar, implicitly the last object name that was selected
  4412. self.inform.emit("")
  4413. else:
  4414. self.call_source = 'app'
  4415. else:
  4416. # If there is no selected object
  4417. # make active the first element of the overlapped objects list
  4418. if self.collection.get_active() is None:
  4419. self.collection.set_active(objects_under_the_click_list[0])
  4420. name_sel_obj = self.collection.get_active().options['name']
  4421. # In case that there is a selected object but it is not in the overlapped object list
  4422. # make that object inactive and activate the first element in the overlapped object list
  4423. if name_sel_obj not in objects_under_the_click_list:
  4424. self.collection.set_inactive(name_sel_obj)
  4425. name_sel_obj = objects_under_the_click_list[0]
  4426. self.collection.set_active(name_sel_obj)
  4427. else:
  4428. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  4429. self.collection.set_all_inactive()
  4430. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  4431. len(objects_under_the_click_list)])
  4432. curr_sel_obj = self.collection.get_active()
  4433. # delete the possible selection box around a possible selected object
  4434. self.delete_selection_shape()
  4435. # create the selection box around the selected object
  4436. self.draw_selection_shape(curr_sel_obj)
  4437. # self.inform.emit('[selected] %s: %s selected' %
  4438. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  4439. if curr_sel_obj.kind == 'gerber':
  4440. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4441. color='green', name=str(curr_sel_obj.options['name'])))
  4442. elif curr_sel_obj.kind == 'excellon':
  4443. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4444. color='brown', name=str(curr_sel_obj.options['name'])))
  4445. elif curr_sel_obj.kind == 'cncjob':
  4446. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4447. color='blue', name=str(curr_sel_obj.options['name'])))
  4448. elif curr_sel_obj.kind == 'geometry':
  4449. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  4450. color='red', name=str(curr_sel_obj.options['name'])))
  4451. # for obj in self.collection.get_list():
  4452. # obj.plot()
  4453. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  4454. # TODO: on selected objects change the object colors and do not draw the selection box
  4455. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  4456. except Exception as e:
  4457. log.error("[ERROR] Something went bad. %s" % str(e))
  4458. return
  4459. def delete_hover_shape(self):
  4460. self.hover_shapes.clear()
  4461. self.hover_shapes.redraw()
  4462. def draw_hover_shape(self, sel_obj, color=None):
  4463. """
  4464. :param sel_obj: the object for which the hover shape must be drawn
  4465. :return:
  4466. """
  4467. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4468. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4469. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4470. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4471. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  4472. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4473. hover_rect = hover_rect.buffer(-0.1)
  4474. hover_rect = hover_rect.buffer(0.2)
  4475. else:
  4476. hover_rect = hover_rect.buffer(-0.00393)
  4477. hover_rect = hover_rect.buffer(0.00787)
  4478. if color:
  4479. face = Color(color)
  4480. face.alpha = 0.2
  4481. outline = Color(color, alpha=0.8)
  4482. else:
  4483. face = Color(self.defaults['global_sel_fill'])
  4484. face.alpha = 0.2
  4485. outline = self.defaults['global_sel_line']
  4486. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  4487. def delete_selection_shape(self):
  4488. self.move_tool.sel_shapes.clear()
  4489. self.move_tool.sel_shapes.redraw()
  4490. def draw_selection_shape(self, sel_obj, color=None):
  4491. """
  4492. :param sel_obj: the object for which the selection shape must be drawn
  4493. :return:
  4494. """
  4495. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  4496. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  4497. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  4498. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  4499. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4500. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4501. sel_rect = sel_rect.buffer(-0.1)
  4502. sel_rect = sel_rect.buffer(0.2)
  4503. else:
  4504. sel_rect = sel_rect.buffer(-0.00393)
  4505. sel_rect = sel_rect.buffer(0.00787)
  4506. if color:
  4507. face = Color(color, alpha=0.2)
  4508. outline = Color(color, alpha=0.8)
  4509. else:
  4510. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  4511. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  4512. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=outline,
  4513. face_color=face, update=True, layer=0, tolerance=None))
  4514. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  4515. """
  4516. :param old_coords: old coordinates
  4517. :param coords: new coordinates
  4518. :return:
  4519. """
  4520. if 'color' in kwargs:
  4521. color = kwargs['color']
  4522. else:
  4523. color = self.defaults['global_sel_line']
  4524. if 'face_color' in kwargs:
  4525. face_color = kwargs['face_color']
  4526. else:
  4527. face_color = self.defaults['global_sel_fill']
  4528. x0, y0 = old_coords
  4529. x1, y1 = coords
  4530. pt1 = (x0, y0)
  4531. pt2 = (x1, y0)
  4532. pt3 = (x1, y1)
  4533. pt4 = (x0, y1)
  4534. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4535. color_t = Color(face_color)
  4536. color_t.alpha = 0.3
  4537. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4538. layer=0, tolerance=None)
  4539. def on_file_new_click(self):
  4540. if self.collection.get_list() and self.should_we_save:
  4541. msgbox = QtWidgets.QMessageBox()
  4542. # msgbox.setText("<B>Save changes ...</B>")
  4543. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  4544. "Creating a New project will delete them.\n"
  4545. "Do you want to Save the project?"))
  4546. msgbox.setWindowTitle(_("Save changes"))
  4547. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4548. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4549. QtWidgets.QMessageBox.No)
  4550. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4551. response = msgbox.exec_()
  4552. if response == QtWidgets.QMessageBox.Yes:
  4553. self.on_file_saveprojectas()
  4554. elif response == QtWidgets.QMessageBox.Cancel:
  4555. return
  4556. self.on_file_new()
  4557. else:
  4558. self.on_file_new()
  4559. self.inform.emit(_("[success] New Project created..."))
  4560. def on_file_new(self):
  4561. """
  4562. Callback for menu item File->New. Returns the application to its
  4563. startup state. This method is thread-safe.
  4564. :return: None
  4565. """
  4566. self.report_usage("on_file_new")
  4567. # Remove everything from memory
  4568. App.log.debug("on_file_new()")
  4569. if self.call_source != 'app':
  4570. self.editor2object(cleanup=True)
  4571. ### EDITOR section
  4572. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  4573. self.exc_editor = FlatCAMExcEditor(self)
  4574. self.grb_editor = FlatCAMGrbEditor(self)
  4575. # Clear pool
  4576. self.clear_pool()
  4577. #delete shapes left drawn from mark shape_collections, if any
  4578. for obj in self.collection.get_list():
  4579. try:
  4580. obj.mark_shapes.enabled = False
  4581. obj.mark_shapes.clear(update=True)
  4582. except:
  4583. pass
  4584. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4585. self.init_tcl()
  4586. self.delete_selection_shape()
  4587. self.collection.delete_all()
  4588. self.setup_component_editor()
  4589. # Clear project filename
  4590. self.project_filename = None
  4591. # Load the application defaults
  4592. self.load_defaults(filename='current_defaults')
  4593. # Re-fresh project options
  4594. self.on_options_app2project()
  4595. # Init Tools
  4596. self.init_tools()
  4597. # Close any Tabs opened in the Plot Tab Area section
  4598. for index in range(self.ui.plot_tab_area.count()):
  4599. self.ui.plot_tab_area.closeTab(index)
  4600. # for whatever reason previous command does not close the last tab so I do it manually
  4601. self.ui.plot_tab_area.closeTab(0)
  4602. # # And then add again the Plot Area
  4603. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4604. self.ui.plot_tab_area.protectTab(0)
  4605. # take the focus of the Notebook on Project Tab.
  4606. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4607. def obj_properties(self):
  4608. self.report_usage("obj_properties()")
  4609. self.properties_tool.run(toggle=False)
  4610. def on_project_context_save(self):
  4611. obj = self.collection.get_active()
  4612. if type(obj) == FlatCAMGeometry:
  4613. self.on_file_exportdxf()
  4614. elif type(obj) == FlatCAMExcellon:
  4615. self.on_file_saveexcellon()
  4616. elif type(obj) == FlatCAMCNCjob:
  4617. obj.on_exportgcode_button_click()
  4618. elif type(obj) == FlatCAMGerber:
  4619. self.on_file_savegerber()
  4620. def obj_move(self):
  4621. self.report_usage("obj_move()")
  4622. self.move_tool.run()
  4623. def on_fileopengerber(self):
  4624. """
  4625. File menu callback for opening a Gerber.
  4626. :return: None
  4627. """
  4628. self.report_usage("on_fileopengerber")
  4629. App.log.debug("on_fileopengerber()")
  4630. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4631. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4632. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  4633. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4634. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4635. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4636. "Allegro Files (*.art);;" \
  4637. "Mentor Files (*.pho *.gdo);;" \
  4638. "All Files (*.*)"
  4639. try:
  4640. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  4641. directory=self.get_last_folder(), filter=_filter_)
  4642. except TypeError:
  4643. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  4644. filenames = [str(filename) for filename in filenames]
  4645. if len(filenames) == 0:
  4646. self.inform.emit(_("[WARNING_NOTCL] Open Gerber cancelled."))
  4647. else:
  4648. for filename in filenames:
  4649. if filename != '':
  4650. self.worker_task.emit({'fcn': self.open_gerber,
  4651. 'params': [filename]})
  4652. def on_fileopenexcellon(self):
  4653. """
  4654. File menu callback for opening an Excellon file.
  4655. :return: None
  4656. """
  4657. self.report_usage("on_fileopenexcellon")
  4658. App.log.debug("on_fileopenexcellon()")
  4659. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4660. "All Files (*.*)"
  4661. try:
  4662. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  4663. directory=self.get_last_folder(), filter=_filter_)
  4664. except TypeError:
  4665. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  4666. filenames = [str(filename) for filename in filenames]
  4667. if len(filenames) == 0:
  4668. self.inform.emit(_("[WARNING_NOTCL] Open Excellon cancelled."))
  4669. else:
  4670. for filename in filenames:
  4671. if filename != '':
  4672. self.worker_task.emit({'fcn': self.open_excellon,
  4673. 'params': [filename]})
  4674. def on_fileopengcode(self):
  4675. """
  4676. File menu call back for opening gcode.
  4677. :return: None
  4678. """
  4679. self.report_usage("on_fileopengcode")
  4680. App.log.debug("on_fileopengcode()")
  4681. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4682. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4683. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4684. "All Files (*.*)"
  4685. try:
  4686. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  4687. directory=self.get_last_folder(), filter=_filter_)
  4688. except TypeError:
  4689. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  4690. filenames = [str(filename) for filename in filenames]
  4691. if len(filenames) == 0:
  4692. self.inform.emit(_("[WARNING_NOTCL] Open G-Code cancelled."))
  4693. else:
  4694. for filename in filenames:
  4695. if filename != '':
  4696. self.worker_task.emit({'fcn': self.open_gcode,
  4697. 'params': [filename]})
  4698. def on_file_openproject(self):
  4699. """
  4700. File menu callback for opening a project.
  4701. :return: None
  4702. """
  4703. self.report_usage("on_file_openproject")
  4704. App.log.debug("on_file_openproject()")
  4705. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4706. try:
  4707. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  4708. directory=self.get_last_folder(), filter=_filter_)
  4709. except TypeError:
  4710. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter = _filter_)
  4711. # The Qt methods above will return a QString which can cause problems later.
  4712. # So far json.dump() will fail to serialize it.
  4713. # TODO: Improve the serialization methods and remove this fix.
  4714. filename = str(filename)
  4715. if filename == "":
  4716. self.inform.emit(_("[WARNING_NOTCL] Open Project cancelled."))
  4717. else:
  4718. # self.worker_task.emit({'fcn': self.open_project,
  4719. # 'params': [filename]})
  4720. # The above was failing because open_project() is not
  4721. # thread safe. The new_project()
  4722. self.open_project(filename)
  4723. def on_file_openconfig(self):
  4724. """
  4725. File menu callback for opening a config file.
  4726. :return: None
  4727. """
  4728. self.report_usage("on_file_openconfig")
  4729. App.log.debug("on_file_openconfig()")
  4730. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4731. try:
  4732. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4733. directory=self.data_path, filter=_filter_)
  4734. except TypeError:
  4735. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  4736. filter = _filter_)
  4737. if filename == "":
  4738. self.inform.emit(_("[WARNING_NOTCL Open Config cancelled."))
  4739. else:
  4740. self.open_config_file(filename)
  4741. def on_file_exportsvg(self):
  4742. """
  4743. Callback for menu item File->Export SVG.
  4744. :return: None
  4745. """
  4746. self.report_usage("on_file_exportsvg")
  4747. App.log.debug("on_file_exportsvg()")
  4748. obj = self.collection.get_active()
  4749. if obj is None:
  4750. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4751. msg = _("Please Select a Geometry object to export")
  4752. msgbox = QtWidgets.QMessageBox()
  4753. msgbox.setInformativeText(msg)
  4754. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4755. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4756. msgbox.exec_()
  4757. return
  4758. # Check for more compatible types and add as required
  4759. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4760. and not isinstance(obj, FlatCAMExcellon)):
  4761. msg = _("[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used.")
  4762. msgbox = QtWidgets.QMessageBox()
  4763. msgbox.setInformativeText(msg)
  4764. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4765. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4766. msgbox.exec_()
  4767. return
  4768. name = self.collection.get_active().options["name"]
  4769. filter = "SVG File (*.svg);;All Files (*.*)"
  4770. try:
  4771. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4772. caption=_("Export SVG"),
  4773. directory=self.get_last_save_folder() + '/' + str(name),
  4774. filter=filter)
  4775. except TypeError:
  4776. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=filter)
  4777. filename = str(filename)
  4778. if filename == "":
  4779. self.inform.emit(_("[WARNING_NOTCL] Export SVG cancelled."))
  4780. return
  4781. else:
  4782. self.export_svg(name, filename)
  4783. self.file_saved.emit("SVG", filename)
  4784. def on_file_exportpng(self):
  4785. self.report_usage("on_file_exportpng")
  4786. App.log.debug("on_file_exportpng()")
  4787. image = _screenshot()
  4788. data = np.asarray(image)
  4789. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4790. self.inform.emit(_('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4'))
  4791. return
  4792. filter_ = "PNG File (*.png);;All Files (*.*)"
  4793. try:
  4794. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4795. caption=_("Export PNG Image"),
  4796. directory=self.get_last_save_folder() + '/png_' + self.date,
  4797. filter=filter_)
  4798. except TypeError:
  4799. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  4800. filename = str(filename)
  4801. if filename == "":
  4802. self.inform.emit(_("Export PNG cancelled."))
  4803. return
  4804. else:
  4805. write_png(filename, data)
  4806. self.file_saved.emit("png", filename)
  4807. def on_file_savegerber(self):
  4808. """
  4809. Callback for menu item File->Export Gerber.
  4810. :return: None
  4811. """
  4812. self.report_usage("on_file_savegerber")
  4813. App.log.debug("on_file_savegerber()")
  4814. obj = self.collection.get_active()
  4815. if obj is None:
  4816. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Gerber object to export."))
  4817. return
  4818. # Check for more compatible types and add as required
  4819. if not isinstance(obj, FlatCAMGerber):
  4820. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files..."))
  4821. return
  4822. name = self.collection.get_active().options["name"]
  4823. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4824. try:
  4825. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4826. caption="Save Gerber source file",
  4827. directory=self.get_last_save_folder() + '/' + name,
  4828. filter=filter)
  4829. except TypeError:
  4830. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=filter)
  4831. filename = str(filename)
  4832. if filename == "":
  4833. self.inform.emit(_("[WARNING_NOTCL] Save Gerber source file cancelled."))
  4834. return
  4835. else:
  4836. self.save_source_file(name, filename)
  4837. self.file_saved.emit("Gerber", filename)
  4838. def on_file_saveexcellon(self):
  4839. """
  4840. Callback for menu item File->Export Gerber.
  4841. :return: None
  4842. """
  4843. self.report_usage("on_file_saveexcellon")
  4844. App.log.debug("on_file_saveexcellon()")
  4845. obj = self.collection.get_active()
  4846. if obj is None:
  4847. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please select an Excellon object to export."))
  4848. return
  4849. # Check for more compatible types and add as required
  4850. if not isinstance(obj, FlatCAMExcellon):
  4851. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4852. return
  4853. name = self.collection.get_active().options["name"]
  4854. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4855. try:
  4856. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4857. caption=_("Save Excellon source file"),
  4858. directory=self.get_last_save_folder() + '/' + name,
  4859. filter=filter)
  4860. except TypeError:
  4861. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=filter)
  4862. filename = str(filename)
  4863. if filename == "":
  4864. self.inform.emit(_("[WARNING_NOTCL] Saving Excellon source file cancelled."))
  4865. return
  4866. else:
  4867. self.save_source_file(name, filename)
  4868. self.file_saved.emit("Excellon", filename)
  4869. def on_file_exportexcellon(self):
  4870. """
  4871. Callback for menu item File->Export SVG.
  4872. :return: None
  4873. """
  4874. self.report_usage("on_file_exportexcellon")
  4875. App.log.debug("on_file_exportexcellon()")
  4876. obj = self.collection.get_active()
  4877. if obj is None:
  4878. self.inform.emit(_("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export."))
  4879. return
  4880. # Check for more compatible types and add as required
  4881. if not isinstance(obj, FlatCAMExcellon):
  4882. self.inform.emit(_("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files..."))
  4883. return
  4884. name = self.collection.get_active().options["name"]
  4885. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4886. try:
  4887. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4888. caption=_("Export Excellon"),
  4889. directory=self.get_last_save_folder() + '/' + name,
  4890. filter=filter)
  4891. except TypeError:
  4892. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=filter)
  4893. filename = str(filename)
  4894. if filename == "":
  4895. self.inform.emit(_("[WARNING_NOTCL] Export Excellon cancelled."))
  4896. return
  4897. else:
  4898. self.export_excellon(name, filename)
  4899. self.file_saved.emit("Excellon", filename)
  4900. def on_file_exportdxf(self):
  4901. """
  4902. Callback for menu item File->Export DXF.
  4903. :return: None
  4904. """
  4905. self.report_usage("on_file_exportdxf")
  4906. App.log.debug("on_file_exportdxf()")
  4907. obj = self.collection.get_active()
  4908. if obj is None:
  4909. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  4910. msg = _("Please Select a Geometry object to export")
  4911. msgbox = QtWidgets.QMessageBox()
  4912. msgbox.setInformativeText(msg)
  4913. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4914. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4915. msgbox.exec_()
  4916. return
  4917. # Check for more compatible types and add as required
  4918. if not isinstance(obj, FlatCAMGeometry):
  4919. msg = _("[ERROR_NOTCL] Only Geometry objects can be used.")
  4920. msgbox = QtWidgets.QMessageBox()
  4921. msgbox.setInformativeText(msg)
  4922. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4923. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4924. msgbox.exec_()
  4925. return
  4926. name = self.collection.get_active().options["name"]
  4927. filter = "DXF File (*.DXF);;All Files (*.*)"
  4928. try:
  4929. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  4930. caption=_("Export DXF"),
  4931. directory=self.get_last_save_folder() + '/' + name,
  4932. filter=filter)
  4933. except TypeError:
  4934. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"), filter=filter)
  4935. filename = str(filename)
  4936. if filename == "":
  4937. self.inform.emit(_("[WARNING_NOTCL] Export DXF cancelled."))
  4938. return
  4939. else:
  4940. self.export_dxf(name, filename)
  4941. self.file_saved.emit("DXF", filename)
  4942. def on_file_importsvg(self, type_of_obj):
  4943. """
  4944. Callback for menu item File->Import SVG.
  4945. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4946. :type type_of_obj: str
  4947. :return: None
  4948. """
  4949. self.report_usage("on_file_importsvg")
  4950. App.log.debug("on_file_importsvg()")
  4951. filter = "SVG File (*.svg);;All Files (*.*)"
  4952. try:
  4953. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  4954. directory=self.get_last_folder(), filter=filter)
  4955. except TypeError:
  4956. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"), filter=filter)
  4957. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4958. type_of_obj = "geometry"
  4959. filenames = [str(filename) for filename in filenames]
  4960. if len(filenames) == 0:
  4961. self.inform.emit(_("[WARNING_NOTCL] Open SVG cancelled."))
  4962. else:
  4963. for filename in filenames:
  4964. if filename != '':
  4965. self.worker_task.emit({'fcn': self.import_svg,
  4966. 'params': [filename, type_of_obj]})
  4967. def on_file_importdxf(self, type_of_obj):
  4968. """
  4969. Callback for menu item File->Import DXF.
  4970. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4971. :type type_of_obj: str
  4972. :return: None
  4973. """
  4974. self.report_usage("on_file_importdxf")
  4975. App.log.debug("on_file_importdxf()")
  4976. filter = "DXF File (*.DXF);;All Files (*.*)"
  4977. try:
  4978. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  4979. directory=self.get_last_folder(), filter=filter)
  4980. except TypeError:
  4981. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"), filter=filter)
  4982. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4983. type_of_obj = "geometry"
  4984. filenames = [str(filename) for filename in filenames]
  4985. if len(filenames) == 0:
  4986. self.inform.emit(_("[WARNING_NOTCL] Open DXF cancelled."))
  4987. else:
  4988. for filename in filenames:
  4989. if filename != '':
  4990. self.worker_task.emit({'fcn': self.import_dxf,
  4991. 'params': [filename, type_of_obj]})
  4992. ###################################################################################################################
  4993. ### The following section has the functions that are displayed are call the Editoe tab CNCJob Tab #################
  4994. ###################################################################################################################
  4995. def init_code_editor(self, name):
  4996. # Signals section
  4997. # Disconnect the old signals
  4998. self.ui.buttonOpen.clicked.disconnect()
  4999. self.ui.buttonSave.clicked.disconnect()
  5000. # add the tab if it was closed
  5001. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _('%s') % name)
  5002. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  5003. # delete the absolute and relative position and messages in the infobar
  5004. self.ui.position_label.setText("")
  5005. self.ui.rel_position_label.setText("")
  5006. # first clear previous text in text editor (if any)
  5007. self.ui.code_editor.clear()
  5008. self.ui.code_editor.setReadOnly(False)
  5009. self.toggle_codeeditor = True
  5010. self.ui.code_editor.completer_enable = False
  5011. # Switch plot_area to CNCJob tab
  5012. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5013. def on_view_source(self):
  5014. try:
  5015. obj = self.collection.get_active()
  5016. except:
  5017. self.inform.emit(_("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source file."))
  5018. return 'fail'
  5019. # then append the text from GCode to the text editor
  5020. try:
  5021. file = StringIO(obj.source_file)
  5022. except AttributeError:
  5023. self.inform.emit(_("[WARNING_NOTCL] There is no selected object for which to see it's source file code."))
  5024. return 'fail'
  5025. if obj.kind == 'gerber':
  5026. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  5027. elif obj.kind == 'excellon':
  5028. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  5029. self.init_code_editor(name=_("Source Editor"))
  5030. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5031. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5032. try:
  5033. for line in file:
  5034. proc_line = str(line).strip('\n')
  5035. self.ui.code_editor.append(proc_line)
  5036. except Exception as e:
  5037. log.debug('App.on_view_source() -->%s' % str(e))
  5038. self.inform.emit(_('[ERROR]App.on_view_source() -->%s') % str(e))
  5039. return
  5040. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5041. self.handleTextChanged()
  5042. self.ui.show()
  5043. def on_toggle_code_editor(self):
  5044. self.report_usage("on_toggle_code_editor()")
  5045. if self.toggle_codeeditor is False:
  5046. self.init_code_editor(name=_("Code Editor"))
  5047. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  5048. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  5049. else:
  5050. for idx in range(self.ui.plot_tab_area.count()):
  5051. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  5052. self.ui.plot_tab_area.closeTab(idx)
  5053. break
  5054. self.toggle_codeeditor = False
  5055. def on_filenewscript(self):
  5056. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5057. self.init_code_editor(name=_("Script Editor"))
  5058. self.ui.code_editor.completer_enable = True
  5059. self.ui.code_editor.append(_(
  5060. "#\n"
  5061. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  5062. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  5063. "#\n\n"
  5064. "# FlatCAM commands list:\n"
  5065. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, Cncjob,\n"
  5066. "# Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames, GetSys,\n"
  5067. "# ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillHoles, Mirror, New,\n"
  5068. "# NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject, Options, Paint, Panelize,\n"
  5069. "# Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,SubtractRectangle, Version,\n"
  5070. "# WriteGCode\n"
  5071. "#\n\n"
  5072. ))
  5073. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  5074. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  5075. self.handleTextChanged()
  5076. self.ui.code_editor.show()
  5077. def on_fileopenscript(self):
  5078. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5079. try:
  5080. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  5081. directory=self.get_last_folder(), filter=_filter_)
  5082. except TypeError:
  5083. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  5084. # The Qt methods above will return a QString which can cause problems later.
  5085. # So far json.dump() will fail to serialize it.
  5086. # TODO: Improve the serialization methods and remove this fix.
  5087. filename = str(filename)
  5088. if filename == "":
  5089. self.inform.emit(_("[WARNING_NOTCL] Open TCL script cancelled."))
  5090. else:
  5091. self.on_filenewscript()
  5092. try:
  5093. with open(filename, "r") as opened_script:
  5094. try:
  5095. for line in opened_script:
  5096. proc_line = str(line).strip('\n')
  5097. self.ui.code_editor.append(proc_line)
  5098. except Exception as e:
  5099. log.debug('App.on_fileopenscript() -->%s' % str(e))
  5100. self.inform.emit(_('[ERROR]App.on_fileopenscript() -->%s') % str(e))
  5101. return
  5102. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5103. self.handleTextChanged()
  5104. self.ui.show()
  5105. except Exception as e:
  5106. log.debug("App.on_fileopenscript() -> %s" % str(e))
  5107. def on_filerunscript(self, name=None):
  5108. """
  5109. File menu callback for loading and running a TCL script.
  5110. :return: None
  5111. """
  5112. self.report_usage("on_filerunscript")
  5113. App.log.debug("on_file_runscript()")
  5114. if name:
  5115. filename = name
  5116. else:
  5117. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  5118. try:
  5119. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  5120. directory=self.get_last_folder(), filter=_filter_)
  5121. except TypeError:
  5122. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  5123. # The Qt methods above will return a QString which can cause problems later.
  5124. # So far json.dump() will fail to serialize it.
  5125. # TODO: Improve the serialization methods and remove this fix.
  5126. filename = str(filename)
  5127. if filename == "":
  5128. self.inform.emit(_("[WARNING_NOTCL] Run TCL script cancelled."))
  5129. else:
  5130. try:
  5131. with open(filename, "r") as tcl_script:
  5132. cmd_line_shellfile_content = tcl_script.read()
  5133. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  5134. except Exception as e:
  5135. log.debug("App.on_filerunscript() -> %s" % str(e))
  5136. sys.exit(2)
  5137. def on_file_saveproject(self):
  5138. """
  5139. Callback for menu item File->Save Project. Saves the project to
  5140. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  5141. if set to None. The project is saved by calling ``self.save_project()``.
  5142. :return: None
  5143. """
  5144. self.report_usage("on_file_saveproject")
  5145. if self.project_filename is None:
  5146. self.on_file_saveprojectas()
  5147. else:
  5148. self.worker_task.emit({'fcn': self.save_project,
  5149. 'params': [self.project_filename]})
  5150. self.file_opened.emit("project", self.project_filename)
  5151. self.file_saved.emit("project", self.project_filename)
  5152. self.should_we_save = False
  5153. def on_file_saveprojectas(self, make_copy=False, thread=True, quit=False):
  5154. """
  5155. Callback for menu item File->Save Project As... Opens a file
  5156. chooser and saves the project to the given file via
  5157. ``self.save_project()``.
  5158. :return: None
  5159. """
  5160. self.report_usage("on_file_saveprojectas")
  5161. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  5162. try:
  5163. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  5164. caption=_("Save Project As ..."),
  5165. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  5166. filter=filter_)
  5167. except TypeError:
  5168. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  5169. filename = str(filename)
  5170. if filename == '':
  5171. self.inform.emit(_("[WARNING_NOTCL] Save Project cancelled."))
  5172. return
  5173. try:
  5174. f = open(filename, 'r')
  5175. f.close()
  5176. exists = True
  5177. except IOError:
  5178. exists = False
  5179. if thread is True:
  5180. self.worker_task.emit({'fcn': self.save_project,
  5181. 'params': [filename, quit]})
  5182. else:
  5183. self.save_project(filename, quit)
  5184. # self.save_project(filename)
  5185. self.file_opened.emit("project", filename)
  5186. self.file_saved.emit("project", filename)
  5187. if not make_copy:
  5188. self.project_filename = filename
  5189. self.should_we_save = False
  5190. def export_svg(self, obj_name, filename, scale_factor=0.00):
  5191. """
  5192. Exports a Geometry Object to an SVG file.
  5193. :param filename: Path to the SVG file to save to.
  5194. :return:
  5195. """
  5196. self.report_usage("export_svg()")
  5197. if filename is None:
  5198. filename = self.defaults["global_last_save_folder"]
  5199. self.log.debug("export_svg()")
  5200. try:
  5201. obj = self.collection.get_by_name(str(obj_name))
  5202. except:
  5203. # TODO: The return behavior has not been established... should raise exception?
  5204. return "Could not retrieve object: %s" % obj_name
  5205. with self.proc_container.new(_("Exporting SVG")) as proc:
  5206. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5207. # Determine bounding area for svg export
  5208. bounds = obj.bounds()
  5209. size = obj.size()
  5210. # Convert everything to strings for use in the xml doc
  5211. svgwidth = str(size[0])
  5212. svgheight = str(size[1])
  5213. minx = str(bounds[0])
  5214. miny = str(bounds[1] - size[1])
  5215. uom = obj.units.lower()
  5216. # Add a SVG Header and footer to the svg output from shapely
  5217. # The transform flips the Y Axis so that everything renders
  5218. # properly within svg apps such as inkscape
  5219. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5220. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5221. svg_header += 'width="' + svgwidth + uom + '" '
  5222. svg_header += 'height="' + svgheight + uom + '" '
  5223. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  5224. svg_header += '<g transform="scale(1,-1)">'
  5225. svg_footer = '</g> </svg>'
  5226. svg_elem = svg_header + exported_svg + svg_footer
  5227. # Parse the xml through a xml parser just to add line feeds
  5228. # and to make it look more pretty for the output
  5229. svgcode = parse_xml_string(svg_elem)
  5230. with open(filename, 'w') as fp:
  5231. fp.write(svgcode.toprettyxml())
  5232. self.file_saved.emit("SVG", filename)
  5233. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5234. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  5235. """
  5236. Exports a Geometry Object to an SVG file in negative.
  5237. :param filename: Path to the SVG file to save to.
  5238. :param: use_thread: If True use threads
  5239. :type: Bool
  5240. :return:
  5241. """
  5242. self.report_usage("export_negative()")
  5243. if filename is None:
  5244. filename = self.defaults["global_last_save_folder"]
  5245. self.log.debug("export_svg() negative")
  5246. try:
  5247. obj = self.collection.get_by_name(str(obj_name))
  5248. except:
  5249. # TODO: The return behavior has not been established... should raise exception?
  5250. return "Could not retrieve object: %s" % obj_name
  5251. try:
  5252. box = self.collection.get_by_name(str(box_name))
  5253. except:
  5254. # TODO: The return behavior has not been established... should raise exception?
  5255. return "Could not retrieve object: %s" % box_name
  5256. if box is None:
  5257. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5258. box = obj
  5259. def make_negative_film():
  5260. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5261. self.progress.emit(40)
  5262. # Determine bounding area for svg export
  5263. bounds = box.bounds()
  5264. size = box.size()
  5265. uom = obj.units.lower()
  5266. # Convert everything to strings for use in the xml doc
  5267. svgwidth = str(size[0] + (2 * boundary))
  5268. svgheight = str(size[1] + (2 * boundary))
  5269. minx = str(bounds[0] - boundary)
  5270. miny = str(bounds[1] + boundary + size[1])
  5271. miny_rect = str(bounds[1] - boundary)
  5272. # Add a SVG Header and footer to the svg output from shapely
  5273. # The transform flips the Y Axis so that everything renders
  5274. # properly within svg apps such as inkscape
  5275. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5276. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5277. svg_header += 'width="' + svgwidth + uom + '" '
  5278. svg_header += 'height="' + svgheight + uom + '" '
  5279. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5280. svg_header += '>'
  5281. svg_header += '<g transform="scale(1,-1)">'
  5282. svg_footer = '</g> </svg>'
  5283. self.progress.emit(60)
  5284. # Change the attributes of the exported SVG
  5285. # We don't need stroke-width - wrong, we do when we have lines with certain width
  5286. # We set opacity to maximum
  5287. # We set the color to WHITE
  5288. root = ET.fromstring(exported_svg)
  5289. for child in root:
  5290. child.set('fill', '#FFFFFF')
  5291. child.set('opacity', '1.0')
  5292. child.set('stroke', '#FFFFFF')
  5293. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  5294. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  5295. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  5296. first_svg_elem_tag = 'rect'
  5297. first_svg_elem_attribs = {
  5298. 'x': minx,
  5299. 'y': miny_rect,
  5300. 'width': svgwidth,
  5301. 'height': svgheight,
  5302. 'id': 'neg_rect',
  5303. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  5304. }
  5305. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  5306. exported_svg = ET.tostring(root)
  5307. svg_elem = svg_header + str(exported_svg) + svg_footer
  5308. self.progress.emit(80)
  5309. # Parse the xml through a xml parser just to add line feeds
  5310. # and to make it look more pretty for the output
  5311. doc = parse_xml_string(svg_elem)
  5312. with open(filename, 'w') as fp:
  5313. fp.write(doc.toprettyxml())
  5314. self.progress.emit(100)
  5315. self.file_saved.emit("SVG", filename)
  5316. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5317. if use_thread is True:
  5318. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5319. def job_thread_film(app_obj):
  5320. try:
  5321. make_negative_film()
  5322. except Exception as e:
  5323. proc.done()
  5324. return
  5325. proc.done()
  5326. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5327. else:
  5328. make_negative_film()
  5329. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  5330. """
  5331. Exports a Geometry Object to an SVG file in negative.
  5332. :param filename: Path to the SVG file to save to.
  5333. :param: use_thread: If True use threads
  5334. :type: Bool
  5335. :return:
  5336. """
  5337. self.report_usage("export_svg_black()")
  5338. if filename is None:
  5339. filename = self.defaults["global_last_save_folder"]
  5340. self.log.debug("export_svg() black")
  5341. try:
  5342. obj = self.collection.get_by_name(str(obj_name))
  5343. except:
  5344. # TODO: The return behavior has not been established... should raise exception?
  5345. return "Could not retrieve object: %s" % obj_name
  5346. try:
  5347. box = self.collection.get_by_name(str(box_name))
  5348. except:
  5349. # TODO: The return behavior has not been established... should raise exception?
  5350. return "Could not retrieve object: %s" % box_name
  5351. if box is None:
  5352. self.inform.emit(_("[WARNING_NOTCL] No object Box. Using instead %s") % obj)
  5353. box = obj
  5354. def make_black_film():
  5355. exported_svg = obj.export_svg(scale_factor=scale_factor)
  5356. self.progress.emit(40)
  5357. # Change the attributes of the exported SVG
  5358. # We don't need stroke-width
  5359. # We set opacity to maximum
  5360. # We set the colour to WHITE
  5361. root = ET.fromstring(exported_svg)
  5362. for child in root:
  5363. child.set('fill', '#000000')
  5364. child.set('opacity', '1.0')
  5365. child.set('stroke', '#000000')
  5366. exported_svg = ET.tostring(root)
  5367. # Determine bounding area for svg export
  5368. bounds = box.bounds()
  5369. size = box.size()
  5370. # This contain the measure units
  5371. uom = obj.units.lower()
  5372. # Define a boundary around SVG of about 1.0mm (~39mils)
  5373. if uom in "mm":
  5374. boundary = 1.0
  5375. else:
  5376. boundary = 0.0393701
  5377. self.progress.emit(80)
  5378. # Convert everything to strings for use in the xml doc
  5379. svgwidth = str(size[0] + (2 * boundary))
  5380. svgheight = str(size[1] + (2 * boundary))
  5381. minx = str(bounds[0] - boundary)
  5382. miny = str(bounds[1] + boundary + size[1])
  5383. self.log.debug(minx)
  5384. self.log.debug(miny)
  5385. # Add a SVG Header and footer to the svg output from shapely
  5386. # The transform flips the Y Axis so that everything renders
  5387. # properly within svg apps such as inkscape
  5388. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  5389. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  5390. svg_header += 'width="' + svgwidth + uom + '" '
  5391. svg_header += 'height="' + svgheight + uom + '" '
  5392. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  5393. svg_header += '>'
  5394. svg_header += '<g transform="scale(1,-1)">'
  5395. svg_footer = '</g> </svg>'
  5396. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  5397. self.progress.emit(90)
  5398. # Parse the xml through a xml parser just to add line feeds
  5399. # and to make it look more pretty for the output
  5400. doc = parse_xml_string(svg_elem)
  5401. with open(filename, 'w') as fp:
  5402. fp.write(doc.toprettyxml())
  5403. self.progress.emit(100)
  5404. self.file_saved.emit("SVG", filename)
  5405. self.inform.emit(_("[success] SVG file exported to %s") % filename)
  5406. if use_thread is True:
  5407. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  5408. def job_thread_film(app_obj):
  5409. try:
  5410. make_black_film()
  5411. except Exception as e:
  5412. proc.done()
  5413. return
  5414. proc.done()
  5415. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  5416. else:
  5417. make_black_film()
  5418. def save_source_file(self, obj_name, filename, use_thread=True):
  5419. """
  5420. Exports a Gerber Object to an Gerber file.
  5421. :param filename: Path to the Gerber file to save to.
  5422. :return:
  5423. """
  5424. self.report_usage("save source file()")
  5425. if filename is None:
  5426. filename = self.defaults["global_last_save_folder"]
  5427. self.log.debug("save source file()")
  5428. obj = self.collection.get_by_name(obj_name)
  5429. file_string = StringIO(obj.source_file)
  5430. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5431. with open(filename, 'w') as file:
  5432. file.writelines('G04*\n')
  5433. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  5434. (obj.kind.upper(), str(self.version), str(self.version_date)))
  5435. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  5436. file.writelines('G04 Created on : %s*\n' % time_string)
  5437. for line in file_string:
  5438. file.writelines(line)
  5439. def export_excellon(self, obj_name, filename, use_thread=True):
  5440. """
  5441. Exports a Excellon Object to an Excellon file.
  5442. :param filename: Path to the Excellon file to save to.
  5443. :return:
  5444. """
  5445. self.report_usage("export_excellon()")
  5446. if filename is None:
  5447. filename = self.defaults["global_last_save_folder"]
  5448. self.log.debug("export_excellon()")
  5449. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  5450. self.defaults["excellon_exp_decimals"]
  5451. )
  5452. units = ''
  5453. try:
  5454. obj = self.collection.get_by_name(str(obj_name))
  5455. except:
  5456. # TODO: The return behavior has not been established... should raise exception?
  5457. return "Could not retrieve object: %s" % obj_name
  5458. # updated units
  5459. eunits = self.defaults["excellon_exp_units"]
  5460. ewhole = self.defaults["excellon_exp_integer"]
  5461. efract = self.defaults["excellon_exp_decimals"]
  5462. ezeros = self.defaults["excellon_exp_zeros"]
  5463. eformat = self.defaults[ "excellon_exp_format"]
  5464. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5465. if fc_units == 'MM':
  5466. factor = 1 if eunits == 'METRIC' else 0.03937
  5467. else:
  5468. factor = 25.4 if eunits == 'METRIC' else 1
  5469. def make_excellon():
  5470. try:
  5471. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  5472. header = 'M48\n'
  5473. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  5474. (str(self.version), str(self.version_date))
  5475. header += ';Filename: %s' % str(obj_name) + '\n'
  5476. header += ';Created on : %s' % time_str + '\n'
  5477. if eformat == 'dec':
  5478. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  5479. header += eunits + '\n'
  5480. for tool in obj.tools:
  5481. if eunits == 'METRIC':
  5482. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5483. tool=str(tool),
  5484. dec=2)
  5485. else:
  5486. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5487. tool=str(tool),
  5488. dec=4)
  5489. else:
  5490. if ezeros == 'LZ':
  5491. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5492. form='ndec', e_zeros='LZ', factor=factor)
  5493. header += '%s,%s\n' % (eunits, 'LZ')
  5494. header += format_exc
  5495. for tool in obj.tools:
  5496. if eunits == 'METRIC':
  5497. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5498. tool=str(tool),
  5499. dec=2)
  5500. else:
  5501. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5502. tool=str(tool),
  5503. dec=4)
  5504. else:
  5505. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  5506. form='ndec', e_zeros='TZ', factor=factor)
  5507. header += '%s,%s\n' % (eunits, 'TZ')
  5508. header += format_exc
  5509. for tool in obj.tools:
  5510. if eunits == 'METRIC':
  5511. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5512. tool=str(tool),
  5513. dec=2)
  5514. else:
  5515. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  5516. tool=str(tool),
  5517. dec=4)
  5518. header += '%\n'
  5519. footer = 'M30\n'
  5520. exported_excellon = header
  5521. exported_excellon += excellon_code
  5522. exported_excellon += footer
  5523. with open(filename, 'w') as fp:
  5524. fp.write(exported_excellon)
  5525. self.file_saved.emit("Excellon", filename)
  5526. self.inform.emit(_("[success] Excellon file exported to %s") % filename)
  5527. except Exception as e:
  5528. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  5529. return 'fail'
  5530. if use_thread is True:
  5531. with self.proc_container.new(_("Exporting Excellon")) as proc:
  5532. def job_thread_exc(app_obj):
  5533. ret = make_excellon()
  5534. if ret == 'fail':
  5535. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5536. return
  5537. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5538. else:
  5539. ret = make_excellon()
  5540. if ret == 'fail':
  5541. self.inform.emit(_('[ERROR_NOTCL] Could not export Excellon file.'))
  5542. return
  5543. def export_dxf(self, obj_name, filename, use_thread=True):
  5544. """
  5545. Exports a Geometry Object to an DXF file.
  5546. :param filename: Path to the DXF file to save to.
  5547. :return:
  5548. """
  5549. self.report_usage("export_dxf()")
  5550. if filename is None:
  5551. filename = self.defaults["global_last_save_folder"]
  5552. self.log.debug("export_dxf()")
  5553. format_exc = ''
  5554. units = ''
  5555. try:
  5556. obj = self.collection.get_by_name(str(obj_name))
  5557. except:
  5558. # TODO: The return behavior has not been established... should raise exception?
  5559. return "Could not retrieve object: %s" % obj_name
  5560. # updated units
  5561. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5562. if units == 'IN' or units == 'INCH':
  5563. units = 'INCH'
  5564. elif units == 'MM' or units == 'METIRC':
  5565. units ='METRIC'
  5566. def make_dxf():
  5567. try:
  5568. dxf_code = obj.export_dxf()
  5569. dxf_code.saveas(filename)
  5570. self.file_saved.emit("DXF", filename)
  5571. self.inform.emit(_("[success] DXF file exported to %s") % filename)
  5572. except:
  5573. return 'fail'
  5574. if use_thread is True:
  5575. with self.proc_container.new(_("Exporting DXF")) as proc:
  5576. def job_thread_exc(app_obj):
  5577. ret = make_dxf()
  5578. if ret == 'fail':
  5579. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5580. return
  5581. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  5582. else:
  5583. ret = make_dxf()
  5584. if ret == 'fail':
  5585. self.inform.emit(_('[[WARNING_NOTCL]] Could not export DXF file.'))
  5586. return
  5587. def import_svg(self, filename, geo_type='geometry', outname=None):
  5588. """
  5589. Adds a new Geometry Object to the projects and populates
  5590. it with shapes extracted from the SVG file.
  5591. :param filename: Path to the SVG file.
  5592. :param outname:
  5593. :return:
  5594. """
  5595. self.report_usage("import_svg()")
  5596. obj_type = ""
  5597. if geo_type is None or geo_type == "geometry":
  5598. obj_type = "geometry"
  5599. elif geo_type == "gerber":
  5600. obj_type = geo_type
  5601. else:
  5602. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5603. "Only Geometry and Gerber are supported"))
  5604. return
  5605. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5606. def obj_init(geo_obj, app_obj):
  5607. geo_obj.import_svg(filename, obj_type, units=units)
  5608. geo_obj.multigeo = False
  5609. with self.proc_container.new(_("Importing SVG")) as proc:
  5610. # Object name
  5611. name = outname or filename.split('/')[-1].split('\\')[-1]
  5612. self.new_object(obj_type, name, obj_init, autoselected=False)
  5613. self.progress.emit(20)
  5614. # Register recent file
  5615. self.file_opened.emit("svg", filename)
  5616. # GUI feedback
  5617. self.inform.emit(_("[success] Opened: %s") % filename)
  5618. self.progress.emit(100)
  5619. def import_dxf(self, filename, geo_type='geometry', outname=None):
  5620. """
  5621. Adds a new Geometry Object to the projects and populates
  5622. it with shapes extracted from the DXF file.
  5623. :param filename: Path to the DXF file.
  5624. :param outname:
  5625. :type putname: str
  5626. :return:
  5627. """
  5628. self.report_usage("import_dxf()")
  5629. obj_type = ""
  5630. if geo_type is None or geo_type == "geometry":
  5631. obj_type = "geometry"
  5632. elif geo_type == "gerber":
  5633. obj_type = geo_type
  5634. else:
  5635. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5636. "Only Geometry and Gerber are supported"))
  5637. return
  5638. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5639. def obj_init(geo_obj, app_obj):
  5640. geo_obj.import_dxf(filename, obj_type, units=units)
  5641. geo_obj.multigeo = False
  5642. with self.proc_container.new(_("Importing DXF")) as proc:
  5643. # Object name
  5644. name = outname or filename.split('/')[-1].split('\\')[-1]
  5645. self.new_object(obj_type, name, obj_init, autoselected=False)
  5646. self.progress.emit(20)
  5647. # Register recent file
  5648. self.file_opened.emit("dxf", filename)
  5649. # GUI feedback
  5650. self.inform.emit(_("[success] Opened: %s") % filename)
  5651. self.progress.emit(100)
  5652. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  5653. """
  5654. Adds a new Geometry Object to the projects and populates
  5655. it with shapes extracted from the SVG file.
  5656. :param filename: Path to the SVG file.
  5657. :param outname:
  5658. :return:
  5659. """
  5660. self.report_usage("import_image()")
  5661. obj_type = ""
  5662. if type is None or type == "geometry":
  5663. obj_type = "geometry"
  5664. elif type == "gerber":
  5665. obj_type = type
  5666. else:
  5667. self.inform.emit(_("[ERROR_NOTCL] Not supported type is picked as parameter. "
  5668. "Only Geometry and Gerber are supported"))
  5669. return
  5670. def obj_init(geo_obj, app_obj):
  5671. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5672. geo_obj.multigeo = False
  5673. with self.proc_container.new(_("Importing Image")) as proc:
  5674. # Object name
  5675. name = outname or filename.split('/')[-1].split('\\')[-1]
  5676. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  5677. self.new_object(obj_type, name, obj_init)
  5678. self.progress.emit(20)
  5679. # Register recent file
  5680. self.file_opened.emit("image", filename)
  5681. # GUI feedback
  5682. self.inform.emit(_("[success] Opened: %s") % filename)
  5683. self.progress.emit(100)
  5684. def open_gerber(self, filename, outname=None):
  5685. """
  5686. Opens a Gerber file, parses it and creates a new object for
  5687. it in the program. Thread-safe.
  5688. :param outname: Name of the resulting object. None causes the
  5689. name to be that of the file.
  5690. :param filename: Gerber file filename
  5691. :type filename: str
  5692. :param follow: If true, the parser will not create polygons, just lines
  5693. following the gerber path.
  5694. :type follow: bool
  5695. :return: None
  5696. """
  5697. # How the object should be initialized
  5698. def obj_init(gerber_obj, app_obj):
  5699. assert isinstance(gerber_obj, FlatCAMGerber), \
  5700. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5701. # Opening the file happens here
  5702. self.progress.emit(30)
  5703. try:
  5704. gerber_obj.parse_file(filename)
  5705. except IOError:
  5706. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to open file: %s") % filename)
  5707. app_obj.progress.emit(0)
  5708. self.inform.emit(_('[ERROR_NOTCL] Failed to open file: %s') % filename)
  5709. return "fail"
  5710. except ParseError as err:
  5711. app_obj.inform.emit(_("[ERROR_NOTCL] Failed to parse file: {name}. {error}").format(name=filename, error=str(err)))
  5712. app_obj.progress.emit(0)
  5713. self.log.error(str(err))
  5714. return "fail"
  5715. except:
  5716. msg = _("[ERROR] An internal error has ocurred. See shell.\n")
  5717. msg += traceback.format_exc()
  5718. app_obj.inform.emit(msg)
  5719. return "fail"
  5720. if gerber_obj.is_empty():
  5721. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5722. # self.collection.set_active(gerber_obj.options["name"])
  5723. # self.collection.delete_active()
  5724. self.inform.emit(_("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation."))
  5725. return "fail"
  5726. # Further parsing
  5727. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5728. App.log.debug("open_gerber()")
  5729. with self.proc_container.new(_("Opening Gerber")) as proc:
  5730. self.progress.emit(10)
  5731. # Object name
  5732. name = outname or filename.split('/')[-1].split('\\')[-1]
  5733. ### Object creation ###
  5734. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5735. if ret == 'fail':
  5736. self.inform.emit(_('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.'))
  5737. return
  5738. # Register recent file
  5739. self.file_opened.emit("gerber", filename)
  5740. self.progress.emit(100)
  5741. # GUI feedback
  5742. self.inform.emit(_("[success] Opened: %s") % filename)
  5743. def open_excellon(self, filename, outname=None):
  5744. """
  5745. Opens an Excellon file, parses it and creates a new object for
  5746. it in the program. Thread-safe.
  5747. :param outname: Name of the resulting object. None causes the
  5748. name to be that of the file.
  5749. :param filename: Excellon file filename
  5750. :type filename: str
  5751. :return: None
  5752. """
  5753. App.log.debug("open_excellon()")
  5754. #self.progress.emit(10)
  5755. # How the object should be initialized
  5756. def obj_init(excellon_obj, app_obj):
  5757. # self.progress.emit(20)
  5758. try:
  5759. ret = excellon_obj.parse_file(filename)
  5760. if ret == "fail":
  5761. log.debug("Excellon parsing failed.")
  5762. self.inform.emit(_("[ERROR_NOTCL] This is not Excellon file."))
  5763. return "fail"
  5764. except IOError:
  5765. app_obj.inform.emit(_("[ERROR_NOTCL] Cannot open file: %s") % filename)
  5766. log.debug("Could not open Excellon object.")
  5767. self.progress.emit(0) # TODO: self and app_bjj mixed
  5768. return "fail"
  5769. except:
  5770. msg = _("[ERROR_NOTCL] An internal error has occurred. See shell.\n")
  5771. msg += traceback.format_exc()
  5772. app_obj.inform.emit(msg)
  5773. return "fail"
  5774. ret = excellon_obj.create_geometry()
  5775. if ret == 'fail':
  5776. log.debug("Could not create geometry for Excellon object.")
  5777. return "fail"
  5778. # if excellon_obj.is_empty():
  5779. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5780. # return "fail"
  5781. for tool in excellon_obj.tools:
  5782. if excellon_obj.tools[tool]['solid_geometry']:
  5783. return
  5784. app_obj.inform.emit(_("[ERROR_NOTCL] No geometry found in file: %s") % filename)
  5785. return "fail"
  5786. with self.proc_container.new(_("Opening Excellon.")):
  5787. # Object name
  5788. name = outname or filename.split('/')[-1].split('\\')[-1]
  5789. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5790. if ret == 'fail':
  5791. self.inform.emit(_('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.'))
  5792. return
  5793. # Register recent file
  5794. self.file_opened.emit("excellon", filename)
  5795. # GUI feedback
  5796. self.inform.emit(_("[success] Opened: %s") % filename)
  5797. # self.progress.emit(100)
  5798. def open_gcode(self, filename, outname=None):
  5799. """
  5800. Opens a G-gcode file, parses it and creates a new object for
  5801. it in the program. Thread-safe.
  5802. :param outname: Name of the resulting object. None causes the
  5803. name to be that of the file.
  5804. :param filename: G-code file filename
  5805. :type filename: str
  5806. :return: None
  5807. """
  5808. App.log.debug("open_gcode()")
  5809. # How the object should be initialized
  5810. def obj_init(job_obj, app_obj_):
  5811. """
  5812. :type app_obj_: App
  5813. """
  5814. assert isinstance(app_obj_, App), \
  5815. "Initializer expected App, got %s" % type(app_obj_)
  5816. self.progress.emit(10)
  5817. try:
  5818. f = open(filename)
  5819. gcode = f.read()
  5820. f.close()
  5821. except IOError:
  5822. app_obj_.inform.emit(_("[ERROR_NOTCL] Failed to open %s") % filename)
  5823. self.progress.emit(0)
  5824. return "fail"
  5825. job_obj.gcode = gcode
  5826. self.progress.emit(20)
  5827. ret = job_obj.gcode_parse()
  5828. if ret == "fail":
  5829. self.inform.emit(_("[ERROR_NOTCL] This is not GCODE"))
  5830. return "fail"
  5831. self.progress.emit(60)
  5832. job_obj.create_geometry()
  5833. with self.proc_container.new(_("Opening G-Code.")):
  5834. # Object name
  5835. name = outname or filename.split('/')[-1].split('\\')[-1]
  5836. # New object creation and file processing
  5837. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5838. if ret == 'fail':
  5839. self.inform.emit(_("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5840. "Attempting to create a FlatCAM CNCJob Object from "
  5841. "G-Code file failed during processing"))
  5842. return "fail"
  5843. # Register recent file
  5844. self.file_opened.emit("cncjob", filename)
  5845. # GUI feedback
  5846. self.inform.emit(_("[success] Opened: %s") % filename)
  5847. self.progress.emit(100)
  5848. def open_config_file(self, filename, run_from_arg=None):
  5849. """
  5850. Loads a config file from the specified file.
  5851. :param filename: Name of the file from which to load.
  5852. :type filename: str
  5853. :return: None
  5854. """
  5855. App.log.debug("Opening config file: " + filename)
  5856. # add the tab if it was closed
  5857. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  5858. # first clear previous text in text editor (if any)
  5859. self.ui.code_editor.clear()
  5860. # Switch plot_area to CNCJob tab
  5861. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5862. try:
  5863. if filename:
  5864. f = QtCore.QFile(filename)
  5865. if f.open(QtCore.QIODevice.ReadOnly):
  5866. stream = QtCore.QTextStream(f)
  5867. gcode_edited = stream.readAll()
  5868. self.ui.code_editor.setPlainText(gcode_edited)
  5869. f.close()
  5870. except IOError:
  5871. App.log.error("Failed to open config file: %s" % filename)
  5872. self.inform.emit(_("[ERROR_NOTCL] Failed to open config file: %s") % filename)
  5873. return
  5874. def open_project(self, filename, run_from_arg=None):
  5875. """
  5876. Loads a project from the specified file.
  5877. 1) Loads and parses file
  5878. 2) Registers the file as recently opened.
  5879. 3) Calls on_file_new()
  5880. 4) Updates options
  5881. 5) Calls new_object() with the object's from_dict() as init method.
  5882. 6) Calls plot_all()
  5883. :param filename: Name of the file from which to load.
  5884. :type filename: str
  5885. :return: None
  5886. """
  5887. App.log.debug("Opening project: " + filename)
  5888. # Open and parse an uncompressed Project file
  5889. try:
  5890. f = open(filename, 'r')
  5891. except IOError:
  5892. App.log.error("Failed to open project file: %s" % filename)
  5893. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5894. return
  5895. try:
  5896. d = json.load(f, object_hook=dict2obj)
  5897. except:
  5898. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s" % filename)
  5899. f.close()
  5900. # Open and parse a compressed Project file
  5901. try:
  5902. with lzma.open(filename) as f:
  5903. file_content = f.read().decode('utf-8')
  5904. d = json.loads(file_content, object_hook=dict2obj)
  5905. except IOError:
  5906. App.log.error("Failed to open project file: %s" % filename)
  5907. self.inform.emit(_("[ERROR_NOTCL] Failed to open project file: %s") % filename)
  5908. return
  5909. self.file_opened.emit("project", filename)
  5910. # Clear the current project
  5911. ## NOT THREAD SAFE ##
  5912. if run_from_arg is True:
  5913. pass
  5914. else:
  5915. self.on_file_new()
  5916. #Project options
  5917. self.options.update(d['options'])
  5918. self.project_filename = filename
  5919. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5920. self.set_screen_units(self.options["units"])
  5921. # Re create objects
  5922. App.log.debug("Re-creating objects...")
  5923. for obj in d['objs']:
  5924. def obj_init(obj_inst, app_inst):
  5925. obj_inst.from_dict(obj)
  5926. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5927. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5928. self.plot_all()
  5929. self.inform.emit(_("[success] Project loaded from: %s") % filename)
  5930. self.should_we_save = False
  5931. App.log.debug("Project loaded")
  5932. def propagate_defaults(self, silent=False):
  5933. """
  5934. This method is used to set default values in classes. It's
  5935. an alternative to project options but allows the use
  5936. of values invisible to the user.
  5937. :return: None
  5938. """
  5939. if silent is False:
  5940. self.log.debug("propagate_defaults()")
  5941. # Which objects to update the given parameters.
  5942. routes = {
  5943. "global_zdownrate": CNCjob,
  5944. "excellon_zeros": Excellon,
  5945. "excellon_format_upper_in": Excellon,
  5946. "excellon_format_lower_in": Excellon,
  5947. "excellon_format_upper_mm": Excellon,
  5948. "excellon_format_lower_mm": Excellon,
  5949. "excellon_units": Excellon,
  5950. "gerber_use_buffer_for_union": Gerber,
  5951. "geometry_multidepth": Geometry
  5952. }
  5953. for param in routes:
  5954. if param in routes[param].defaults:
  5955. try:
  5956. routes[param].defaults[param] = self.defaults[param]
  5957. if silent is False:
  5958. self.log.debug(" " + param + " OK")
  5959. except KeyError:
  5960. if silent is False:
  5961. self.log.debug(" ERROR: " + param + " not in defaults.")
  5962. else:
  5963. # Try extracting the name:
  5964. # classname_param here is param in the object
  5965. if param.find(routes[param].__name__.lower() + "_") == 0:
  5966. p = param[len(routes[param].__name__) + 1:]
  5967. if p in routes[param].defaults:
  5968. routes[param].defaults[p] = self.defaults[param]
  5969. if silent is False:
  5970. self.log.debug(" " + param + " OK!")
  5971. def restore_main_win_geom(self):
  5972. try:
  5973. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5974. self.defaults["global_def_win_y"],
  5975. self.defaults["global_def_win_w"],
  5976. self.defaults["global_def_win_h"])
  5977. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  5978. settings = QSettings("Open Source", "FlatCAM")
  5979. if settings.contains("maximized_gui"):
  5980. maximized_ui = settings.value('maximized_gui', type=bool)
  5981. if maximized_ui is True:
  5982. self.ui.showMaximized()
  5983. except KeyError as e:
  5984. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  5985. def plot_all(self, zoom=True):
  5986. """
  5987. Re-generates all plots from all objects.
  5988. :return: None
  5989. """
  5990. self.log.debug("Plot_all()")
  5991. for obj in self.collection.get_list():
  5992. def worker_task(obj):
  5993. with self.proc_container.new("Plotting"):
  5994. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5995. if zoom:
  5996. self.object_plotted.emit(obj)
  5997. # Send to worker
  5998. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5999. # self.progress.emit(10)
  6000. #
  6001. # def worker_task(app_obj):
  6002. # print "worker task"
  6003. # percentage = 0.1
  6004. # try:
  6005. # delta = 0.9 / len(self.collection.get_list())
  6006. # except ZeroDivisionError:
  6007. # self.progress.emit(0)
  6008. # return
  6009. # for obj in self.collection.get_list():
  6010. # with self.proc_container.new("Plotting"):
  6011. # obj.plot()
  6012. # app_obj.object_plotted.emit(obj)
  6013. #
  6014. # percentage += delta
  6015. # self.progress.emit(int(percentage*100))
  6016. #
  6017. # self.progress.emit(0)
  6018. # self.plots_updated.emit()
  6019. #
  6020. # # Send to worker
  6021. # #self.worker.add_task(worker_task, [self])
  6022. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6023. def register_folder(self, filename):
  6024. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  6025. def register_save_folder(self, filename):
  6026. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  6027. def set_progress_bar(self, percentage, text=""):
  6028. self.ui.progress_bar.setValue(int(percentage))
  6029. def setup_shell(self):
  6030. """
  6031. Creates shell functions. Runs once at startup.
  6032. :return: None
  6033. """
  6034. self.log.debug("setup_shell()")
  6035. def shelp(p=None):
  6036. if not p:
  6037. return _("Available commands:\n") + \
  6038. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  6039. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  6040. if p not in commands:
  6041. return "Unknown command: %s" % p
  6042. return commands[p]["help"]
  6043. # --- Migrated to new architecture ---
  6044. # def options(name):
  6045. # ops = self.collection.get_by_name(str(name)).options
  6046. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  6047. def h(*args):
  6048. """
  6049. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  6050. and standalone parameters into list.
  6051. """
  6052. kwa = {}
  6053. a = []
  6054. n = len(args)
  6055. name = None
  6056. for i in range(n):
  6057. match = re.search(r'^-([a-zA-Z].*)', args[i])
  6058. if match:
  6059. assert name is None
  6060. name = match.group(1)
  6061. continue
  6062. if name is None:
  6063. a.append(args[i])
  6064. else:
  6065. kwa[name] = args[i]
  6066. name = None
  6067. return a, kwa
  6068. @contextmanager
  6069. def wait_signal(signal, timeout=10000):
  6070. """
  6071. Block loop until signal emitted, timeout (ms) elapses
  6072. or unhandled exception happens in a thread.
  6073. :param signal: Signal to wait for.
  6074. """
  6075. loop = QtCore.QEventLoop()
  6076. # Normal termination
  6077. signal.connect(loop.quit)
  6078. # Termination by exception in thread
  6079. self.thread_exception.connect(loop.quit)
  6080. status = {'timed_out': False}
  6081. def report_quit():
  6082. status['timed_out'] = True
  6083. loop.quit()
  6084. yield
  6085. # Temporarily change how exceptions are managed.
  6086. oeh = sys.excepthook
  6087. ex = []
  6088. def except_hook(type_, value, traceback_):
  6089. ex.append(value)
  6090. oeh(type_, value, traceback_)
  6091. sys.excepthook = except_hook
  6092. # Terminate on timeout
  6093. if timeout is not None:
  6094. QtCore.QTimer.singleShot(timeout, report_quit)
  6095. #### Block ####
  6096. loop.exec_()
  6097. # Restore exception management
  6098. sys.excepthook = oeh
  6099. if ex:
  6100. self.raiseTclError(str(ex[0]))
  6101. if status['timed_out']:
  6102. raise Exception('Timed out!')
  6103. def make_docs():
  6104. output = ''
  6105. import collections
  6106. od = collections.OrderedDict(sorted(commands.items()))
  6107. for cmd_, val in od.items():
  6108. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  6109. t = val['help']
  6110. usage_i = t.find('>')
  6111. if usage_i < 0:
  6112. expl = t
  6113. output += expl + '\n\n'
  6114. continue
  6115. expl = t[:usage_i - 1]
  6116. output += expl + '\n\n'
  6117. end_usage_i = t[usage_i:].find('\n')
  6118. if end_usage_i < 0:
  6119. end_usage_i = len(t[usage_i:])
  6120. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  6121. else:
  6122. extras = t[usage_i+end_usage_i+1:]
  6123. parts = [s.strip() for s in extras.split('\n')]
  6124. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  6125. for p in parts:
  6126. output += ' ' + p + '\n\n'
  6127. return output
  6128. '''
  6129. Howto implement TCL shell commands:
  6130. All parameters passed to command should be possible to set as None and test it afterwards.
  6131. This is because we need to see error caused in tcl,
  6132. if None value as default parameter is not allowed TCL will return empty error.
  6133. Use:
  6134. def mycommand(name=None,...):
  6135. Test it like this:
  6136. if name is None:
  6137. self.raise_tcl_error('Argument name is missing.')
  6138. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  6139. otherwise we will miss it and processing will silently continue.
  6140. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  6141. which is catched in exec_command and displayed in TCL shell console with red background.
  6142. Error in console is displayed with TCL trace.
  6143. This behavior works only within main thread,
  6144. errors with promissed tasks can be catched and detected only with log.
  6145. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  6146. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  6147. '''
  6148. commands = {
  6149. 'help': {
  6150. 'fcn': shelp,
  6151. 'help': _("Shows list of commands.")
  6152. },
  6153. }
  6154. # Import/overwrite tcl commands as objects of TclCommand descendants
  6155. # This modifies the variable 'commands'.
  6156. tclCommands.register_all_commands(self, commands)
  6157. # Add commands to the tcl interpreter
  6158. for cmd in commands:
  6159. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  6160. # Make the tcl puts function return instead of print to stdout
  6161. self.tcl.eval('''
  6162. rename puts original_puts
  6163. proc puts {args} {
  6164. if {[llength $args] == 1} {
  6165. return "[lindex $args 0]"
  6166. } else {
  6167. eval original_puts $args
  6168. }
  6169. }
  6170. ''')
  6171. def setup_recent_items(self):
  6172. # TODO: Move this to constructor
  6173. icons = {
  6174. "gerber": "share/flatcam_icon16.png",
  6175. "excellon": "share/drill16.png",
  6176. "cncjob": "share/cnc16.png",
  6177. "project": "share/project16.png",
  6178. "svg": "share/geometry16.png",
  6179. "dxf": "share/dxf16.png",
  6180. "image": "share/image16.png"
  6181. }
  6182. openers = {
  6183. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  6184. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  6185. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  6186. 'project': self.open_project,
  6187. 'svg': self.import_svg,
  6188. 'dxf': self.import_dxf,
  6189. 'image': self.import_image
  6190. }
  6191. # Open file
  6192. try:
  6193. f = open(self.data_path + '/recent.json')
  6194. except IOError:
  6195. App.log.error("Failed to load recent item list.")
  6196. self.inform.emit(_("[ERROR_NOTCL] Failed to load recent item list."))
  6197. return
  6198. try:
  6199. self.recent = json.load(f)
  6200. except json.scanner.JSONDecodeError:
  6201. App.log.error("Failed to parse recent item list.")
  6202. self.inform.emit(_("[ERROR_NOTCL] Failed to parse recent item list."))
  6203. f.close()
  6204. return
  6205. f.close()
  6206. # Closure needed to create callbacks in a loop.
  6207. # Otherwise late binding occurs.
  6208. def make_callback(func, fname):
  6209. def opener():
  6210. func(fname)
  6211. return opener
  6212. def reset_recent():
  6213. # Reset menu
  6214. self.ui.recent.clear()
  6215. self.recent = []
  6216. try:
  6217. f = open(self.data_path + '/recent.json', 'w')
  6218. except IOError:
  6219. App.log.error("Failed to open recent items file for writing.")
  6220. return
  6221. json.dump(self.recent, f)
  6222. # Reset menu
  6223. self.ui.recent.clear()
  6224. # Create menu items
  6225. for recent in self.recent:
  6226. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  6227. try:
  6228. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  6229. # Attach callback
  6230. o = make_callback(openers[recent["kind"]], recent['filename'])
  6231. action.triggered.connect(o)
  6232. self.ui.recent.addAction(action)
  6233. except KeyError:
  6234. App.log.error("Unsupported file type: %s" % recent["kind"])
  6235. # Last action in Recent Files menu is one that Clear the content
  6236. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  6237. clear_action.triggered.connect(reset_recent)
  6238. self.ui.recent.addSeparator()
  6239. self.ui.recent.addAction(clear_action)
  6240. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  6241. # self.ui.menufilerecent.set_submenu(recent_menu)
  6242. # recent_menu.show_all()
  6243. # self.ui.recent.show()
  6244. self.log.debug("Recent items list has been populated.")
  6245. def setup_component_editor(self):
  6246. # label = QtWidgets.QLabel("Choose an item from Project")
  6247. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  6248. sel_title = QtWidgets.QTextEdit(
  6249. _('<b>Shortcut Key List</b>'))
  6250. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6251. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6252. # font = self.sel_title.font()
  6253. # font.setPointSize(12)
  6254. # self.sel_title.setFont(font)
  6255. selected_text = _('''
  6256. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  6257. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6258. The normal flow when working in FlatCAM is the following:</span></p>
  6259. <ol>
  6260. <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 />
  6261. <br />
  6262. 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 />
  6263. &nbsp;</li>
  6264. <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 />
  6265. <br />
  6266. 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 />
  6267. <br />
  6268. You can change the parameters in this screen and the flow direction is like this:<br />
  6269. <br />
  6270. <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>
  6271. </ol>
  6272. <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>
  6273. ''')
  6274. sel_title.setText(selected_text)
  6275. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6276. self.ui.selected_scroll_area.setWidget(sel_title)
  6277. # tool_title = QtWidgets.QTextEdit(
  6278. # '<b>Shortcut Key List</b>')
  6279. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  6280. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  6281. # # font = self.sel_title.font()
  6282. # # font.setPointSize(12)
  6283. # # self.sel_title.setFont(font)
  6284. #
  6285. # tool_text = '''
  6286. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  6287. #
  6288. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  6289. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  6290. #
  6291. # <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 />
  6292. # 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>
  6293. #
  6294. # <ol>
  6295. # </ol>
  6296. #
  6297. # <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>
  6298. #
  6299. # '''
  6300. #
  6301. # tool_title.setText(tool_text)
  6302. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  6303. #
  6304. # self.ui.tool_scroll_area.setWidget(tool_title)
  6305. def setup_obj_classes(self):
  6306. """
  6307. Sets up application specifics on the FlatCAMObj class.
  6308. :return: None
  6309. """
  6310. FlatCAMObj.app = self
  6311. ObjectCollection.app = self
  6312. FCProcess.app = self
  6313. FCProcessContainer.app = self
  6314. def version_check(self):
  6315. """
  6316. Checks for the latest version of the program. Alerts the
  6317. user if theirs is outdated. This method is meant to be run
  6318. in a separate thread.
  6319. :return: None
  6320. """
  6321. self.log.debug("version_check()")
  6322. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  6323. full_url = App.version_url + \
  6324. "?s=" + str(self.defaults['global_serial']) + \
  6325. "&v=" + str(self.version) + \
  6326. "&os=" + str(self.os) + \
  6327. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  6328. else:
  6329. # no_stats dict; just so it won't break things on website
  6330. no_ststs_dict = {}
  6331. no_ststs_dict["global_ststs"] = {}
  6332. full_url = App.version_url + \
  6333. "?s=" + str(self.defaults['global_serial']) + \
  6334. "&v=" + str(self.version) + \
  6335. "&os=" + str(self.os) + \
  6336. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  6337. App.log.debug("Checking for updates @ %s" % full_url)
  6338. ### Get the data
  6339. try:
  6340. f = urllib.request.urlopen(full_url)
  6341. except:
  6342. # App.log.warning("Failed checking for latest version. Could not connect.")
  6343. self.log.warning("Failed checking for latest version. Could not connect.")
  6344. self.inform.emit(_("[WARNING_NOTCL] Failed checking for latest version. Could not connect."))
  6345. return
  6346. try:
  6347. data = json.load(f)
  6348. except Exception as e:
  6349. App.log.error("Could not parse information about latest version.")
  6350. self.inform.emit(_("[ERROR_NOTCL] Could not parse information about latest version."))
  6351. App.log.debug("json.load(): %s" % str(e))
  6352. f.close()
  6353. return
  6354. f.close()
  6355. ### Latest version?
  6356. if self.version >= data["version"]:
  6357. App.log.debug("FlatCAM is up to date!")
  6358. self.inform.emit(_("[success] FlatCAM is up to date!"))
  6359. return
  6360. App.log.debug("Newer version available.")
  6361. self.message.emit(
  6362. _("Newer Version Available"),
  6363. _("There is a newer version of FlatCAM available for download:\n\n") +
  6364. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  6365. _("info")
  6366. )
  6367. def on_zoom_fit(self, event):
  6368. """
  6369. Callback for zoom-out request. This can be either from the corresponding
  6370. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  6371. with axes limits from the geometry bounds of all objects.
  6372. :param event: Ignored.
  6373. :return: None
  6374. """
  6375. self.plotcanvas.fit_view()
  6376. def disable_all_plots(self):
  6377. self.report_usage("disable_all_plots()")
  6378. self.disable_plots(self.collection.get_list())
  6379. self.inform.emit(_("[success] All plots disabled."))
  6380. def disable_other_plots(self):
  6381. self.report_usage("disable_other_plots()")
  6382. self.disable_plots(self.collection.get_non_selected())
  6383. self.inform.emit(_("[success] All non selected plots disabled."))
  6384. def enable_all_plots(self):
  6385. self.report_usage("enable_all_plots()")
  6386. self.enable_plots(self.collection.get_list())
  6387. self.inform.emit(_("[success] All plots enabled."))
  6388. # TODO: FIX THIS
  6389. '''
  6390. By default this is not threaded
  6391. If threaded the app give warnings like this:
  6392. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6393. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6394. '''
  6395. def enable_plots(self, objects, threaded=False):
  6396. if threaded is True:
  6397. def worker_task(app_obj):
  6398. percentage = 0.1
  6399. try:
  6400. delta = 0.9 / len(objects)
  6401. except ZeroDivisionError:
  6402. self.progress.emit(0)
  6403. return
  6404. for obj in objects:
  6405. obj.options['plot'] = True
  6406. percentage += delta
  6407. self.progress.emit(int(percentage*100))
  6408. self.progress.emit(0)
  6409. self.plots_updated.emit()
  6410. self.collection.update_view()
  6411. # Send to worker
  6412. # self.worker.add_task(worker_task, [self])
  6413. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6414. else:
  6415. for obj in objects:
  6416. obj.options['plot'] = True
  6417. self.progress.emit(0)
  6418. self.plots_updated.emit()
  6419. self.collection.update_view()
  6420. # TODO: FIX THIS
  6421. '''
  6422. By default this is not threaded
  6423. If threaded the app give warnings like this:
  6424. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  6425. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  6426. '''
  6427. def disable_plots(self, objects, threaded=False):
  6428. # TODO: This method is very similar to replot_all. Try to merge.
  6429. """
  6430. Disables plots
  6431. :param objects: list
  6432. Objects to be disabled
  6433. :return:
  6434. """
  6435. if threaded is True:
  6436. self.progress.emit(10)
  6437. def worker_task(app_obj):
  6438. percentage = 0.1
  6439. try:
  6440. delta = 0.9 / len(objects)
  6441. except ZeroDivisionError:
  6442. self.progress.emit(0)
  6443. return
  6444. for obj in objects:
  6445. obj.options['plot'] = False
  6446. percentage += delta
  6447. self.progress.emit(int(percentage*100))
  6448. self.progress.emit(0)
  6449. self.plots_updated.emit()
  6450. self.collection.update_view()
  6451. # Send to worker
  6452. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  6453. else:
  6454. for obj in objects:
  6455. obj.options['plot'] = False
  6456. self.plots_updated.emit()
  6457. self.collection.update_view()
  6458. def clear_plots(self):
  6459. objects = self.collection.get_list()
  6460. for obj in objects:
  6461. obj.clear(obj == objects[-1])
  6462. # Clear pool to free memory
  6463. self.clear_pool()
  6464. def generate_cnc_job(self, objects):
  6465. self.report_usage("generate_cnc_job()")
  6466. # for obj in objects:
  6467. # obj.generatecncjob()
  6468. for obj in objects:
  6469. obj.on_generatecnc_button_click()
  6470. def save_project(self, filename, quit=False):
  6471. """
  6472. Saves the current project to the specified file.
  6473. :param filename: Name of the file in which to save.
  6474. :type filename: str
  6475. :return: None
  6476. """
  6477. self.log.debug("save_project()")
  6478. self.save_in_progress = True
  6479. with self.proc_container.new(_("Saving FlatCAM Project")) as proc:
  6480. ## Capture the latest changes
  6481. # Current object
  6482. try:
  6483. self.collection.get_active().read_form()
  6484. except:
  6485. self.log.debug("There was no active object")
  6486. pass
  6487. # Project options
  6488. self.options_read_form()
  6489. # Serialize the whole project
  6490. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  6491. "options": self.options,
  6492. "version": self.version}
  6493. if self.defaults["global_save_compressed"] is True:
  6494. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  6495. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  6496. # # Write
  6497. f.write(g)
  6498. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6499. else:
  6500. # Open file
  6501. try:
  6502. f = open(filename, 'w')
  6503. except IOError:
  6504. App.log.error("Failed to open file for saving: %s", filename)
  6505. return
  6506. # Write
  6507. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  6508. f.close()
  6509. # verification of the saved project
  6510. # Open and parse
  6511. try:
  6512. saved_f = open(filename, 'r')
  6513. except IOError:
  6514. self.inform.emit(_("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it.") % filename)
  6515. return
  6516. try:
  6517. saved_d = json.load(saved_f, object_hook=dict2obj)
  6518. except:
  6519. self.inform.emit(
  6520. _("[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it.") % filename)
  6521. f.close()
  6522. return
  6523. saved_f.close()
  6524. if 'version' in saved_d:
  6525. self.inform.emit(_("[success] Project saved to: %s") % filename)
  6526. else:
  6527. self.inform.emit(_("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it.") % filename)
  6528. if quit:
  6529. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  6530. # t.start()
  6531. self.start_delayed_quit(delay=500, filename=filename)
  6532. def start_delayed_quit(self, delay, filename):
  6533. """
  6534. :param delay: period of checking if project file size is more than zero; in seconds
  6535. :param filename: the name of the project file to be checked periodically for size more than zero
  6536. :return:
  6537. """
  6538. self.quit_timer = QtCore.QTimer()
  6539. self.quit_timer.setInterval(delay)
  6540. self.quit_timer.timeout.connect(lambda : self.check_project_file_size(filename=filename))
  6541. self.quit_timer.start()
  6542. def check_project_file_size(self, filename):
  6543. """
  6544. :param filename: the name of the project file to be checked periodically for size more than zero
  6545. :return:
  6546. """
  6547. try:
  6548. if os.stat(filename).st_size > 0:
  6549. self.quit_timer.stop()
  6550. self.app_quit.emit()
  6551. except Exception:
  6552. traceback.print_exc()
  6553. def on_options_app2project(self):
  6554. """
  6555. Callback for Options->Transfer Options->App=>Project. Copies options
  6556. from application defaults to project defaults.
  6557. :return: None
  6558. """
  6559. self.report_usage("on_options_app2project")
  6560. self.defaults_read_form()
  6561. self.options.update(self.defaults)
  6562. self.options_write_form()
  6563. def on_options_project2app(self):
  6564. """
  6565. Callback for Options->Transfer Options->Project=>App. Copies options
  6566. from project defaults to application defaults.
  6567. :return: None
  6568. """
  6569. self.report_usage("on_options_project2app")
  6570. self.options_read_form()
  6571. self.defaults.update(self.options)
  6572. self.defaults_write_form()
  6573. def on_options_project2object(self):
  6574. """
  6575. Callback for Options->Transfer Options->Project=>Object. Copies options
  6576. from project defaults to the currently selected object.
  6577. :return: None
  6578. """
  6579. self.report_usage("on_options_project2object")
  6580. self.options_read_form()
  6581. obj = self.collection.get_active()
  6582. if obj is None:
  6583. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6584. return
  6585. for option in self.options:
  6586. if option.find(obj.kind + "_") == 0:
  6587. oname = option[len(obj.kind) + 1:]
  6588. obj.options[oname] = self.options[option]
  6589. obj.to_form() # Update UI
  6590. def on_options_object2project(self):
  6591. """
  6592. Callback for Options->Transfer Options->Object=>Project. Copies options
  6593. from the currently selected object to project defaults.
  6594. :return: None
  6595. """
  6596. self.report_usage("on_options_object2project")
  6597. obj = self.collection.get_active()
  6598. if obj is None:
  6599. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6600. return
  6601. obj.read_form()
  6602. for option in obj.options:
  6603. if option in ['name']: # TODO: Handle this better...
  6604. continue
  6605. self.options[obj.kind + "_" + option] = obj.options[option]
  6606. self.options_write_form()
  6607. def on_options_object2app(self):
  6608. """
  6609. Callback for Options->Transfer Options->Object=>App. Copies options
  6610. from the currently selected object to application defaults.
  6611. :return: None
  6612. """
  6613. self.report_usage("on_options_object2app")
  6614. obj = self.collection.get_active()
  6615. if obj is None:
  6616. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6617. return
  6618. obj.read_form()
  6619. for option in obj.options:
  6620. if option in ['name']: # TODO: Handle this better...
  6621. continue
  6622. self.defaults[obj.kind + "_" + option] = obj.options[option]
  6623. self.defaults_write_form()
  6624. def on_options_app2object(self):
  6625. """
  6626. Callback for Options->Transfer Options->App=>Object. Copies options
  6627. from application defaults to the currently selected object.
  6628. :return: None
  6629. """
  6630. self.report_usage("on_options_app2object")
  6631. self.defaults_read_form()
  6632. obj = self.collection.get_active()
  6633. if obj is None:
  6634. self.inform.emit(_("[WARNING_NOTCL] No object selected."))
  6635. return
  6636. for option in self.defaults:
  6637. if option.find(obj.kind + "_") == 0:
  6638. oname = option[len(obj.kind) + 1:]
  6639. obj.options[oname] = self.defaults[option]
  6640. obj.to_form() # Update UI
  6641. # end of file