FlatCAMApp.py 364 KB

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