FlatCAMApp.py 361 KB

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