FlatCAMApp.py 388 KB

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