FlatCAMApp.py 360 KB

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