FlatCAMApp.py 382 KB

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